Dvorak
Dvorak

Dvorak Chen

All Posts in 2024.8


supplement of Authentication

# Authentication Failure Handling in .NET In my recent blog post titled ".NET Authentication and Authorization," I discussed the configuration and implementation of authentication and authorization in a .NET application. However, I failed to address an important aspect: handling authentication failures. By default, the authentication configuration in .NET uses a cookie policy. When an authentication failure occurs, it responds with a 302 status code and redirects to the `/Account/Login` page. This poses a problem when the frontend and backend of the application are separated, as the redirect will not point to the correct address. For instance, let's assume the frontend app is hosted at `localhost:8800` and the backend app at `localhost:9900`. If an authentication failure occurs during a frontend API request, the response will contain a 302 status code with the location set to `localhost:9900/Account/Login`. The frontend, using HTTP APIs like `fetch` or `Axios`, will automatically fol...--GPT 4

.NET

dotnet Authentication and Authorization

# .NET身份验证和授权 本篇博客介绍了在.NET中的身份验证和授权。使用了基于Cookie的身份验证,即用户身份信息将存储在Cookie中并响应给客户端。在控制器中,通过创建一个包含用户身份信息的`ClaimsPrincipal`对象,并使用`SignIn(claimsPrincipal, CookieAuthenticationDefaults.AuthenticationScheme)`方法将其发送给客户端: ```csharp var claims = new List<Claim> { new(ClaimTypes.Sid, <Id>,ClaimValueTypes.Sid, ISSUER, ISSUER), new(ClaimTypes.Email, <Email>, ClaimValueTypes.Email, ISSUER, ISSUER) }; var claimsIdentity = new ClaimsIdentity( claims, CookieAuthenticationDefaults.AuthenticationScheme); var claimsPrincipal = new ClaimsPrincipal(claimsIdentity); return SignIn(claimsPrincipal, CookieAuthenticationDefaults.AuthenticationScheme); ``` `SignIn`方法将创建一个包含Cookie的`SignInResult`对象,并将其从控制器返回给客户端,你可以在响应中看到`set-cookie`头部: ![file](/image/img-b9fca940-08db-4696-9537-d76aecf8a553.png) ## 我更喜欢使用Cookie 有多种身份验证方式可供选择,例如:Cookie、JWT等。如果我使用基于浏览器的客户端,我更倾向于使用Cookie,例如Web、Tauri、Electron等。 因为现代浏览器具有更高的安全性,它们会自动处理Cookie,接收Cookie并存储Cookie,并在发送请求时附加Cookie。客户端不需要额外处理Cookie。 相比之下,JWT会更加复杂。 包含用户身份信息的Cookie可...--GPT 4

.NET