目录
- 认证授权
- 身份认证
- 授权
- 默认授权
- 选择授权
- 总结
开发了一个公司内部系统,使用asp.net core 3.1。在开发用户认证授权使用的是简单的cookie认证方式,然后开发好了要写几个接口给其它系统调用数据。并且只是几个简单的接口不准备再重新部署一个站点,所以就直接在mvc的项目里面加了一个api区域用来写接口。这时候因为是接口所以就不能用cookie方式进行认证,得加一个jwt认证,采用多种身份验证方案来进行认证授权。
认证授权
身份验证是确定用户身份的过程。 授权是确定用户是否有权访问资源的过程。 在 asp.net core 中,身份验证由 iauthenticationservice 负责,而它供身份验证中间件使用。 身份验证服务会使用已注册的身份验证处理程序来完成与身份验证相关的操作。
认证–>授权
关于认证授权我们要区分认证和授权是两个概念,具体可查看msdn官方文档也可以搜索其它文章看看,讲的很多。其中包括oauth 2.0 以及jwt的相关知识都有很多资料并且讲解的很好。
身份认证
身份验证方案由 startup.configureservices 中的注册身份验证服务指定:
方式是在调用 services.addauthentication 后调用方案特定的扩展方法(例如 addjwtbearer 或 addcookie)。 这些扩展方法使用 authenticationbuilder.addscheme 向适当的设置注册方案。
添加cookie jwtbearer验证方案
public void configureservices(iservicecollection services)
{
services.addsession();
services.addmvc(o =>
{
o.filters.add(typeof(myexceptionfilterattribute));// 全局异常filter
}).addrazorruntimecompilation();
//添加身份认证方案
var jwtconfig= configuration.getsection("jwt").get<jwtconfig>();
services.addauthentication
(authoption =>{
//指定默认选项
authoption.defaultchallengescheme= cookieauthenticationdefaults.authenticationscheme;
authoption.defaultauthenticatescheme = cookieauthenticationdefaults.authenticationscheme;
authoption.defaultsignoutscheme = cookieauthenticationdefaults.authenticationscheme;
authoption.defaultsigninscheme= cookieauthenticationdefaults.authenticationscheme;
})
.addcookie(cookieauthenticationdefaults.authenticationscheme, option =>
{
option.cookie.name = "adcookie";//设置存储用户登录信息(用户token信息)的cookie名称
option.cookie.httponly = true;//设置存储用户登录信息(用户token信息)的cookie,无法通过客户端浏览器脚本(如javascript等)访问到
option.expiretimespan = timespan.fromdays(3);// 过期时间
option.slidingexpiration = true;// 是否在过期时间过半的时候,自动延期
option.loginpath = "/account/login";
option.logoutpath = "/account/loginout";
})
.addjwtbearer(option =>
{
option.tokenvalidationparameters = new tokenvalidationparameters
{
validissuer = jwtconfig.issuer,
validaudience = jwtconfig.audience,
validateissuer = true,
validatelifetime = jwtconfig.validatelifetime,
issuersigningkey = new symmetricsecuritykey(encoding.utf8.getbytes(jwtconfig.signingkey)),
//缓冲过期时间,总的有效时间等于这个时间加上jwt的过期时间
clockskew = timespan.fromseconds(0)
};
});
}
jwtbearer认证的配置参数类jwtconfig
public class jwtconfig
{
/// <summary>
/// 谁颁发的
/// </summary>
public string issuer { get; set; }
/// <summary>
/// 颁发给谁
/// </summary>
public string audience { get; set; }
/// <summary>
/// 令牌密码
/// a secret that needs to be at least 16 characters long
/// </summary>
public string signingkey { get; set; }
/// <summary>
/// 过期时间(分钟)
/// </summary>
public int expires { get; set; }
/// <summary>
/// 是否校验过期时间
/// </summary>
public bool validatelifetime { get; set; }
}
appsettings.json 配置参数
"jwt": {
"issuer": "issuer",
"audience": "audience",
"signingkey": "c0d32c63-z43d-4917-bbc2-5e726d087452",
//过期时间(分钟)
"expires": 10080,
//是否验证过期时间
"validatelifetime": true
}
添加身份验证中间件
通过在应用的 iapplicationbuilder 上调用 useauthentication 扩展方法,在 startup.configure 中添加身份验证中间件。 如果调用 useauthentication,会注册使用之前注册的身份验证方案的中间节。 请在依赖于要进行身份验证的用户的所有中间件之前调用 useauthentication。 如果使用终结点路由,则必须按以下顺序调用 useauthentication:
- 在 userouting之后调用,以便路由信息可用于身份验证决策。
- 在 useendpoints 之前调用,以便用户在经过身份验证后才能访问终结点。
public void configure(iapplicationbuilder app, iwebhostenvironment env)
{
if (env.isdevelopment())
{
app.usedeveloperexceptionpage();
}
else
{
app.useexceptionhandler("/home/error");
app.usehsts();
}
app.usehttpsredirection();
app.usesession();
app.userouting();
//开启认证中间件
app.useauthentication();
//开启授权中间件
app.useauthorization();
app.useendpoints(endpoints =>
{
endpoints.mapcontrollerroute(
name: "areas",
pattern: "{area:exists}/{controller=home}/{action=index}/{id?}");
endpoints.mapcontrollerroute(
name: "default",
pattern: "{controller=home}/{action=index}/{id?}");
});
}
cookie认证
[httppost]
public async task<newtonsoftjsonresult> loginin(string username, string userpassword, string code)
{
ajaxresult objajaxresult = new ajaxresult();
var user = _userbll.getuser(username, userpassword);
if (user == null)
{
objajaxresult.result = doresult.noauthorization;
objajaxresult.promptmsg = "用户名或密码错误";
}
else
{
var claims = new list<claim>
{
new claim("username", username),
new claim("userid",user.id.tostring()),
};
await httpcontext.signinasync(new claimsprincipal(new claimsidentity(claims,cookieauthenticationdefaults.authenticationscheme)));
objajaxresult.result = doresult.success;
objajaxresult.promptmsg = "登录成功";
}
return new newtonsoftjsonresult(objajaxresult);
}
jwt认证
[httppost]
public newtonsoftjsonresult token([frombody] userinfo model)
{
ajaxresult objajaxresult = new ajaxresult();
var user = _userbll.getuser(model.username, model.password);
if (user == null)
{
objajaxresult.result = doresult.noauthorization;
objajaxresult.promptmsg = "用户名或密码错误";
}
else
{
//jwttokenoptions 是通过配置获取上面配置的参数信息
var jwttokenoptions = baseconfigmodel.jwtconfig;
var key = new symmetricsecuritykey(encoding.utf8.getbytes(jwttokenoptions.signingkey));
var credentials = new signingcredentials(key, securityalgorithms.hmacsha256);
//身份
var claims = new list<claim>
{
new claim("userid",user.id.tostring()),
new claim("username",user.username),
};
//令牌
var expires = datetime.now.addminutes(jwttokenoptions.expires);
var token = new jwtsecuritytoken(
issuer: jwttokenoptions.issuer,
audience: jwttokenoptions.audience,
claims: claims,
notbefore: datetime.now,
expires: expires,
signingcredentials: credentials
);
string jwttoken = new jwtsecuritytokenhandler().writetoken(token);
objajaxresult.result = doresult.success;
objajaxresult.retvalue = new
{
token = jwttoken
};
objajaxresult.promptmsg = "登录成功";
}
return new newtonsoftjsonresult(objajaxresult);
}
授权
在授权时,应用指示要使用的处理程序。 选择应用程序将通过以逗号分隔的身份验证方案列表传递到来授权的处理程序 [authorize] 。 [authorize]属性指定要使用的身份验证方案或方案,不管是否配置了默认。
默认授权
因为上面认证配置中我们使用cookie作为默认配置,所以前端对应的controller就不用指定验证方案,直接打上[authorize]即可。
选择授权
对于api接口我们使用jwt授权,在controller上打上指定方案。
[authorize(authenticationschemes = jwtbearerdefaults.authenticationscheme)]
总结
关于多种方案混合验证授权的流程:
1、配置认证方案(相关的配置参数可采用配置文件形式)。
2、添加授权验证中间件。
3、提供认证接口。
4、配置需要授权的接口授权方案。
到此这篇关于asp.net core3.1cookie和jwt混合认证授权实现多种身份验证方案的文章就介绍到这了,更多相关asp.net core cookie和jwt认证授权内容请搜索www.887551.com以前的文章或继续浏览下面的相关文章希望大家以后多多支持www.887551.com!