Authorization and certification
Authentication is to verify whether the user is legal, that is to verify whether the user’s authentication information is correct; authorization is to verify whether the authenticated user has the authority to do something. We use JWT for authentication and authorization.
Why use JWT for authentication and authorization?
A complete system usually includes authentication and authorization, so only users who provide correct authentication information and have operation authority can access the system, thus realizing the protection of the system.
. NETCORE API using JWT experience
Generate a token token:
[HttpGet]
public ActionResult<IEnumerable<string>> Get()
{
//Simply create a token token token
//Create declaration array
var claims = new Claim[]
{
new Claim(ClaimTypes.Name, "pwai"),
new Claim(JwtRegisteredClaimNames.Email, "[email protected]"),
new Claim(Jwt RegisteredClaimNames.Sub "," 1 "), // subject is ID uid
};
//Instantiate token object
var key = new SymmetricSecurityKey( Encoding.UTF8 . GetBytes ("winrtwinrtwinrtwinrtwinrt"); // at least 16 bit key
var token = new JwtSecurityToken(
issuer: " http://localhost : 5000 ", // the publisher is our current project
audience: " http://localhost : 5001 ", // subscribe, which item do we need to use this token
claims: claims,
expires: DateTime.Now.AddHours(1),
signingCredentials: new SigningCredentials(key, SecurityAlgorithms.HmacSha256)
);
//Generating token
var jwtToken = new JwtSecurityTokenHandler().WriteToken(token);
return new string[] { jwtToken };
}
To enable bearer authentication and register jwtbearer:
public void ConfigureServices(IServiceCollection services)
{
//Clear jwtsecuritytokenn. Net core forbids JWT from configuration mapping SecurityTokenHandler.DefaultInboundClaimTypeMap .Clear();
//The authentication logic should be the same as the previous logic for generating token token
var symmetricKeyAsBase64 = "winrtwinrtwinrtwinrt";
var keyByteArray = Encoding.ASCII.GetBytes(symmetricKeyAsBase64);
var signingKey = new SymmetricSecurityKey(keyByteArray);
var tokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = signingKey,
ValidateIssuer = true,
ValidIssuer = " http://localhost : 5000 ", // publisher
ValidateAudience = true,
ValidAudience = " http://localhost : 5001 ", // subscriber
ValidateLifetime = true,
ClockSkew = TimeSpan.FromSeconds(30),
RequireExpirationTime = true,
};
services.AddAuthentication("Bearer")
.AddJwtBearer(o =>
{
o.TokenValidationParameters = tokenValidationParameters;
});
}
Open the authorization middleware:
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
//Method context omits other middleware
app.UseAuthentication();
}
Get token token:
[HttpGet("{jwtStr}")]
[authorize] // authorization
public ActionResult<IEnumerable<string>> Get(string jwtStr)
{
//Method of getting token content
//Method 1
var jwtHandler = new JwtSecurityTokenHandler();
JwtSecurityToken jwtToken = jwtHandler.ReadJwtToken(jwtStr);
//Method 2
var sub = User.FindFirst(d => d.Type == "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name")?.Value;
//Method 3
var name = _accessor.HttpContext.User.Identity.Name;
var claims= _accessor.HttpContext.User.Claims;
var claimTypeVal= (from item in claims
where item.Type == JwtRegisteredClaimNames.Email
select item.Value).ToList();
return new string[] { JsonConvert.SerializeObject(jwtToken), sub, name, JsonConvert.SerializeObject(claimTypeVal) };
}
Test with postman:
requesthttp://localhost: 5000 / API / values /, get token
requesthttp://localhost: 5000 / API / values / (copy the token just obtained) eyjhbgcioijiujiujii1niisiinr5cci6ikpxvcj9.eyjodhrdhrwoi8vc2nozw1hcy54bwxb2f2fwlm9yzy93cy8yymda1lzl2lkzw50a xr5l2nsyyltcy9uy1w1sisisiimvtyywllsi2hkh4djb20lcjb20lcjwii, I, I, I, and I, 6i6ikpxvcj9.eyjodhwoi8vcj9.eyjodhi8vcy2nozwy54bwx2fb2fwlm9yzy93cy8yymda1lymda1l2lkzzzzwzzzzzw9yzy93cy8cy8yymda1l2lkzzzzw50wizxhwijoxnja2mdyymtm4lcjpc3mioijodhrwoi 8vbg9jywxob3n0ojuwmdailcjhdwqioijodhrwoi 8vbg 9jywxob3n0 OjUwMDEifQ.quIqR -OBWXiPJ8r3myymrqzt g5Bd1xyIfIl0P_ Whunc
At the same time, HTTP authentication is added to the request header. When the client uses the specified authentication method and provides the correct authentication information, that is, the authorization item is added to the request header. At this time, when the resource is accessed again, the server will verify the information provided by the user.
The cognitive use pattern of bearer was as follows: 1Authorization: Bearer <bearer_token>
After sending the request, you can view the result of the serialized token: