Asp.Net Core 2.0+接入IdentityServer Admin并配置角色role控制访问

1     增加API接口服务

1.1   新增普通asp.net core 站点。

新增XxxxController在任一接口方法头加Authorize并指定角色。

 1 [Authorize(Roles = "FreeUser,Admin")]
 2 
 3 [HttpGet]
 4 
 5 public IActionResult Get()
 6 
 7 {
 8 
 9     return new JsonResult(from c in User.Claims select new { c.Type, c.Value });
10 
11 }

 

1.2   启动项配置

1.2.1 在Startup.ConfigureServices方法中添加如下内容:

 1 // 添加权限验证
 2 
 3 services.AddMvcCore()
 4 
 5     .AddAuthorization()
 6 
 7     .AddJsonFormatters();
 8 
 9 // 添加认证配置
10 
11 services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
12 
13 .AddIdentityServerAuthentication(options =>
14 
15 {
16 
17     options.Authority = "https://localhost:5001"; // 认证站点地址
18 
19     options.RequireHttpsMetadata = false;
20 
21     options.ApiName = "api1";
22 
23     options.RoleClaimType = JwtClaimTypes.Role;
24 
25 });
26 
27 // 配置跨站
28 
29 services.AddCors(options =>
30 
31 {
32 
33     // this defines a CORS policy called "default"
34 
35     options.AddPolicy("default", policy =>
36 
37     {
38 
39         policy.WithOrigins("https://localhost:5007") // JS站点服务
40 
41             .AllowAnyHeader()
42 
43             .AllowAnyMethod();
44 
45     });
46 
47 });

 

 

 

1.2.2 启动项配置Startup.Configure方法中添加如下内容:

1 app.UseCors("default");
2 
3 app.UseAuthentication();
4 
5 app.UseMvc();

 

2     添加Js客户端

新建js项目,请参考官方文档(https://identityserver4.readthedocs.io/en/release/quickstarts/7_javascript_client.html)

2.1   安装依赖

oidc-client。

2.2   新增Html如下:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title></title>
</head>
<body>
    <button id="login">Login</button>
    <button id="api">Call API</button>
    <button id="logout">Logout</button>
    <pre id="results"></pre>
    <script src="oidc-client.js"></script>
    <script src="app.js"></script>
</body>
</html>
 
    

2.3   app.js内容如下:

  1 function log() {
  2 
  3     document.getElementById('results').innerText = '';
  4 
  5  
  6 
  7     Array.prototype.forEach.call(arguments, function (msg) {
  8 
  9         if (msg instanceof Error) {
 10 
 11             msg = "Error: " + msg.message;
 12 
 13         }
 14 
 15         else if (typeof msg !== 'string') {
 16 
 17             msg = JSON.stringify(msg, null, 2);
 18 
 19         }
 20 
 21         document.getElementById('results').innerHTML += msg + '\r\n';
 22 
 23     });
 24 
 25 }
 26 
 27  
 28 
 29 document.getElementById("login").addEventListener("click", login, false);
 30 
 31 document.getElementById("api").addEventListener("click", api, false);
 32 
 33 document.getElementById("logout").addEventListener("click", logout, false);
 34 
 35  
 36 
 37 var config = {
 38 
 39     authority: "https://localhost:5001", // 认证服务器
 40 
 41     client_id: "js",
 42 
 43     redirect_uri: "https://localhost:5007/callback.html", // 当前JS站点
 44 
 45     response_type: "id_token token",
 46 
 47     scope:"openid profile api1",
 48 
 49     post_logout_redirect_uri : "https://localhost:5007/index.html", // 当前JS站点
 50 
 51 };
 52 
 53 var mgr = new Oidc.UserManager(config);
 54 
 55 mgr.getUser().then(function (user) {
 56 
 57     if (user) {
 58 
 59         log("User logged in", user.profile);
 60 
 61     }
 62 
 63     else {
 64 
 65         log("User not logged in");
 66 
 67     }
 68 
 69 });
 70 
 71  
 72 
 73 function login() {
 74 
 75     mgr.signinRedirect();
 76 
 77 }
 78 
 79  
 80 
 81 function api() {
 82 
 83     mgr.getUser().then(function (user) {
 84 
 85         var url = "https://localhost:5003/identity"; // 要访问的API接口站
 86 
 87  
 88 
 89         var xhr = new XMLHttpRequest();
 90 
 91         xhr.open("GET", url);
 92 
 93         xhr.onload = function() {
 94 
 95             log(xhr.status, JSON.parse(xhr.responseText));
 96 
 97         };
 98 
 99         xhr.setRequestHeader("Authorization", "Bearer " + user.access_token);
100 
101         xhr.send();
102 
103     });
104 
105 }
106 
107  
108 
109 function logout() {
110 
111     mgr.signoutRedirect();
112 
113 }
 
    

2.4   新增回调页面如下:

 1 <!DOCTYPE html>
 2 
 3 <html>
 4 
 5 <head>
 6 
 7     <meta charset="utf-8" />
 8 
 9     <title>JS客户端回调页面</title>
10 
11 </head>
12 
13 <body>
14 
15     <script src="oidc-client.js"></script>
16 
17     <script>
18 
19         new Oidc.UserManager().signinRedirectCallback().then(function () {
20 
21             window.location = "index.html";
22 
23         }).catch(function (e) {
24 
25             console.error(e);
26 
27         });
28 
29     </script>
30 
31 </body>
32 
33 </html>

 

 

 

3     安装配置IdentityServerAdmin服务

使用模板创建项目,源码地址(https://github.com/IdentityServer/IdentityServer4.Templates)。

3.1   安装模板

dotnet new -i identityserver4.templates

 

3.2   创建项目

3.2.1 新增目录

mkdir UserCenter

cd UseCenter

 

3.2.2 使用模板生成项目

dotnet new is4admin

打开项目,并运行。

配置角色

 

 配置用户

 

设置用户角色

 

新增受保护资源

需要在声明中添加role。

 

 

新增JS客户端配置

配置URL

 

添加可访问的资源

 

posted on 2019-01-11 16:19 Tryc 阅读( ...) 评论( ...) 编辑 收藏

转载于:https://www.cnblogs.com/tryc/p/10255678.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
ASP.NET Core IdentityASP.NET Core 框架提供的一种身份认证和授权框架,它可以用于管理用户、角色和权限。 下面是使用 ASP.NET Core Identity 的步骤: 1. 首先,要在 ASP.NET Core 项目中安装 Microsoft.AspNetCore.Identity 包。 2. 接着,在 Startup.cs 文件中配置 Identity 服务。可以使用 AddIdentity() 方法来配置 Identity,默认情况下会将 Identity 存储在内存中,但这并不适合生产环境。因此,我们需要配置 Identity 存储提供程序。例如,可以使用 Entity Framework Core 来存储 Identity 数据。如果要使用 Entity Framework Core,可以使用 AddEntityFrameworkStores() 方法将 Identity 存储在数据库中。 ```csharp public void ConfigureServices(IServiceCollection services) { // 添加 Identity 服务 services.AddIdentity<IdentityUser, IdentityRole>() .AddEntityFrameworkStores<ApplicationDbContext>() .AddDefaultTokenProviders(); // 添加其他服务 services.AddControllersWithViews(); } ``` 3. 然后,需要创建一个 ApplicationDbContext 类来表示 Identity 数据库上下文。这个类需要继承 IdentityDbContext 类,并指定 IdentityUser 和 IdentityRole 类型。 ```csharp public class ApplicationDbContext : IdentityDbContext<IdentityUser, IdentityRole, string> { public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options) { } } ``` 4. 在 ConfigureServices() 方法中,还需要配置身份认证和授权选项。例如,可以配置密码复杂性要求、登录尝试锁定、cookie 配置等等。 ```csharp public void ConfigureServices(IServiceCollection services) { // 添加 Identity 服务 services.AddIdentity<IdentityUser, IdentityRole>() .AddEntityFrameworkStores<ApplicationDbContext>() .AddDefaultTokenProviders(); // 配置身份认证和授权选项 services.Configure<IdentityOptions>(options => { // 密码复杂性要求 options.Password.RequireDigit = true; options.Password.RequireLowercase = true; options.Password.RequireNonAlphanumeric = true; options.Password.RequireUppercase = true; options.Password.RequiredLength = 8; // 登录尝试锁定 options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(5); options.Lockout.MaxFailedAccessAttempts = 5; // cookie 配置 options.Cookies.ApplicationCookie.ExpireTimeSpan = TimeSpan.FromDays(7); options.Cookies.ApplicationCookie.LoginPath = "/Account/Login"; options.Cookies.ApplicationCookie.LogoutPath = "/Account/Logout"; }); // 添加其他服务 services.AddControllersWithViews(); } ``` 5. 最后,在应用程序中使用 Identity API 来管理用户、角色和权限。例如,可以在控制器中使用 UserManager 和 RoleManager 类来创建、删除和修改用户和角色。 ```csharp public class AccountController : Controller { private readonly UserManager<IdentityUser> _userManager; private readonly SignInManager<IdentityUser> _signInManager; private readonly RoleManager<IdentityRole> _roleManager; public AccountController(UserManager<IdentityUser> userManager, SignInManager<IdentityUser> signInManager, RoleManager<IdentityRole> roleManager) { _userManager = userManager; _signInManager = signInManager; _roleManager = roleManager; } public IActionResult Register() { return View(); } [HttpPost] public async Task<IActionResult> Register(RegisterViewModel model) { if (ModelState.IsValid) { var user = new IdentityUser { UserName = model.Email, Email = model.Email }; var result = await _userManager.CreateAsync(user, model.Password); if (result.Succeeded) { await _signInManager.SignInAsync(user, isPersistent: false); return RedirectToAction("Index", "Home"); } foreach (var error in result.Errors) { ModelState.AddModelError(string.Empty, error.Description); } } return View(model); } public async Task<IActionResult> CreateRole() { var result = await _roleManager.CreateAsync(new IdentityRole("Admin")); if (result.Succeeded) { return Ok(); } return BadRequest(); } } ``` 以上就是使用 ASP.NET Core Identity 来管理用户和角色的步骤。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值