asp.net core web api authentication and authorization code example
Example 1: asp net core identity bearer token authentication example
[HttpPost]
public async Task<IActionResult> AccessToken([FromForm]string code, [FromForm]string grant_type, [FromForm]string redirect_uri, [FromForm]string client_id, [FromForm]string client_secret)
{
if (grant_type != "authorization_code")
{
return Redirect(redirect_uri + "?error=unsupported_response_type");
}
if (!clientValidator.Valid(client_id, client_secret))
{
return Redirect(redirect_uri + "?error=access_denied");
}
string previous_uri = codeAndURIStorage.Load(code);
string user = codeAndUserStorage.Load(code);
codeAndURIStorage.Delete(code);
codeAndUserStorage.Delete(code);
if (redirect_uri != previous_uri)
{
return BadRequest("'redirect_uri' was inconsistent.");
}
if (user == null)
{
return BadRequest("Couldn't find user associated with the given code.");
}
var symmetricSecurityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["TokenOptions:Key"]))
var tokenHandler = new JwtSecurityTokenHandler();
var tokenDescriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(new Claim[]
{
new Claim(ClaimTypes.Name, user)
}),
Expires = DateTime.UtcNow.AddYears(2),
Issuer = "MyWebsite.com",
Audience = "MyWebsite.com",
SigningCredentials = new SigningCredentials(symmetricSecurityKey, SecurityAlgorithms.HmacSha256Signature)
};
var token = tokenHandler.CreateToken(tokenDescriptor);
var access_token = tokenHandler.WriteToken(token);
return Ok(new { access_token, token_type="bearer" });
}
Example 2: asp.net core oauth token authentication
public void ConfigureServices(IServiceCollection services)
{
services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true)
.AddEntityFrameworkStores<ApplicationDbContext>();
services.AddAuthentication()
.AddMicrosoftAccount(microsoftOptions =>
{
microsoftOptions.ClientId = Configuration["Authentication:Microsoft:ClientId"];
microsoftOptions.ClientSecret = Configuration["Authentication:Microsoft:ClientSecret"];
})
.AddGoogle(googleOptions => { ... })
.AddTwitter(twitterOptions => { ... })
.AddFacebook(facebookOptions => { ... });
}