新建API的項目web
dotnet new webapi --name ClientCredentialApiapi
在咱們上一節課的代碼IdentityServerSample中加入受權的認證post
引入命名空間:ui
using Microsoft.AspNetCore.Authorization;spa
而後給Controller加上authrize的屬性。這樣API就訪問不了。3d
給咱們剛建立的項目:ClientCredentialApicode
加上Authrize屬性,這樣這個API咱們就訪問不了。blog
nuget包添加引用token
IdentityServer4.AccessTokenValidationci
在Startup.cs裏面把認證受權加進來
services.AddAuthentication("Bearer") .AddIdentityServerAuthentication(options => { options.Authority = "http://localhost:5000";//須要受權的時候找誰 options.RequireHttpsMetadata = false; options.ApiName = "api"; });
使用Authentication
這樣就完成了。有了IdentityServer在APi端加受權就很是的簡單
換成501的端口
而後不用Https:
http://localhost:5001/api/values
返回的狀體是401,未受權
那咱們去哪裏拿Token呢?
運行起來Server端 的地址。
打開地址:
http://localhost:5000/.well-known/openid-configuration
這裏告訴咱們取token的地址
"token_endpoint": "http://localhost:5000/connect/token",
postman內請求這個地址:
http://localhost:5000/connect/token
body內三個參數:
client_id:client
client_secret:secret
grant_type:client_credentials
返回的數據。這樣就拿到了咱們的token
{ "access_token": "eyJhbGciOiJSUzI1NiIsImtpZCI6ImE3MGZkOGQyYjVjMmVlNDUzMWU1ZGUyNWJmYTViNmE4IiwidHlwIjoiSldUIn0.eyJuYmYiOjE1NTIyMzY5ODEsImV4cCI6MTU1MjI0MDU4MSwiaXNzIjoiaHR0cDovL2xvY2FsaG9zdDo1MDAwIiwiYXVkIjpbImh0dHA6Ly9sb2NhbGhvc3Q6NTAwMC9yZXNvdXJjZXMiLCJhcGkiXSwiY2xpZW50X2lkIjoiY2xpZW50Iiwic2NvcGUiOlsiYXBpIl19.GNX-gMxDDTzniaamYw9mOC159XfnP9AlkynOpYqvjSZJCduM6aqRIiwVbvMsak8GZhShPZpGggj8_ng5S-81M-VNbSlce5SImHckMXkBGXJ4A9OgsYemja7d3Mv-Lz43DkgWvTnoX1CfZl8PxBDueYlZOSLlqwlmYkN3S0TYuQwgXD0nKLyEnRTWy8meOAOkpuGzSabIcXBGwetMRrNZeooRtvYDuEe6d_Jfxi0o2-KD-TehB7n70D7ZFGnjTG2Ka5oJQrBKdaqY-Mqt42unJeV-faMhvjYkCxHqxRGtnue2zaCWWJdxP1wDu5VSRZjdfD4LoB29wfOwYeJxAalgvw", "expires_in": 3600, "token_type": "Bearer" }
複製從服務端拿到的token的值。
訪問地址:
http://localhost:5001/api/values
Authorization:Bearer+空格+複製過來的Token
這個token就是從是服務端 5000端口的地址拿過來的token
這是postman去實現的。接下來咱們要寫一個api的方式去實現