在 Startup.cs 文件中添加以下代码:
services.AddAuthentication(options =>
{
options.DefaultScheme = "Cookies";
options.DefaultChallengeScheme = "OpenIdConnect";
})
.AddCookie("Cookies")
.AddOpenIdConnect("OpenIdConnect", options =>
{
options.Authority = "https://example.com";
options.ClientId = "client_id";
options.ClientSecret = "client_secret";
options.ResponseType = "code";
});
这里使用了 OpenID Connect 作为身份验证的 OWIN 中间件,并配置了一个“cookie”认证方案。 在 Web API 控制器中,我们可以使用 [Authorize] 特性来强制进行身份验证:
[Authorize(AuthenticationSchemes = "Cookies")]
public class MyController : ApiController
{
// ...
}
在 Angular 服务中,首先要注入 HttpClient,然后使用 HttpClient 发送 HTTP 请求时,设置请求头的 withCredentials
选项为 true,这样就会在请求头中包含身份验证 cookie:
import { HttpClient } from '@angular/common/http';
@Injectable()
export class DataService {
constructor(private http: HttpClient) { }
getData() {
return this.http.get('/api/data', { withCredentials: true });
}
}
这里使用的是 Angular 的 HttpClient 服务,并在发出 GET 请求时使用 withCredentials: true
选项来指示要包含身份验证 cookie。
当我在 Web API 中收到一个请求时,可以检查身份验证 cookie 是否存在,以确定用户是否已经身份验证:
[HttpGet]
public HttpResponseMessage GetData()
{
if (Request.Cookies[FormsAuthentication.FormsCookieName] == null)
return Request.CreateResponse(HttpStatusCode.Unauthorized);
// 用户已经身份验证
return Request.CreateResponse(HttpStatusCode.OK, "Hello, world!");
}
这个例子检