15-oauth2+oidc实现Server部分

1-我们使用之前项目的mvcCookieAuthSampe2进行改造

1.1  增加IdentityServer4

2-增加Config.cs文件,对IdentityServer提供相关的配置数据

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using IdentityServer4.Test;
using IdentityServer4.Models;
using IdentityServer4;

namespace MvcCookieAuthSample
{
    public class Config
    {
        public static IEnumerable<ApiResource> GetApiResources() {
            return new List<ApiResource>() {
                 new ApiResource("api1","api DisplayName")
            };
        }

        public static IEnumerable<Client> GetClients()
        {
            return new List<Client>() {
                 new Client(){
                     ClientId="mvc",
                      AllowedGrantTypes= GrantTypes.Implicit,
                      ClientSecrets= new List<Secret>(){
                          new Secret("secret".Sha256())
                      },
                      RedirectUris = {"http://localhost:5001/signin-oidc" },
                      PostLogoutRedirectUris = { "http://localhost/signout-callback-oidc"},
                      RequireConsent=false,
                      AllowedScopes={
                         IdentityServerConstants.StandardScopes.Profile,
                          IdentityServerConstants.StandardScopes.OpenId
                      }
                 }
            };
        }

        public static IEnumerable<IdentityResource> GetIdentityResources()
        {
            return new List<IdentityResource>() {
                new IdentityResources.OpenId(),
                new IdentityResources.Email(),
                new IdentityResources.Profile()
            };
        }

        public static List<TestUser> GetTestUsers()
        {
            return new List<TestUser>() {
                 new TestUser(){
                       SubjectId="oa001",
                       Username="qinzb",
                       Password="123456"
                 }
            };
        }

    }
}

2-在Startup.cs文件启用IdentityServer

 public void ConfigureServices(IServiceCollection services)
        {
            services.AddIdentityServer()
            .AddDeveloperSigningCredential()
            .AddInMemoryApiResources(Config.GetApiResources())
            .AddInMemoryClients(Config.GetClients())
            .AddInMemoryIdentityResources(Config.GetIdentityResources())
            .AddTestUsers(Config.GetTestUsers())  ;
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
        }
public void Configure(IApplicationBuilder app, IHostingEnvironment env) { app.UseIdentityServer(); //主要加了这段代码启用Identity4 app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); }

 

3-在AccountController.cs提供登陆功能

        private TestUserStore _testUserStore;
        public AccountController(TestUserStore testUserStore)
        {
            _testUserStore = testUserStore;
        }

        public IActionResult Login(string returnUrl = null)
        {
            ViewData["returnUrl"] = returnUrl;
            return View();
        }

        [HttpPost]
        public async Task<IActionResult> Login(ViewModel.LoginViewModel loginModel, string returnUrl = null)
        {
            var findUser = _testUserStore.FindByUsername(loginModel.UserName);
            //  string returnUrl = Request.Form["returnUrl"];
            if (findUser == null)
            {
                ModelState.AddModelError(nameof(loginModel.UserName), "用户不存在");
            }
            else
            {
                if (_testUserStore.ValidateCredentials(loginModel.UserName, loginModel.Password))
                {
                    var profiles = new AuthenticationProperties()
                    {
                        IsPersistent = true,
                        ExpiresUtc = System.DateTimeOffset.UtcNow.Add(TimeSpan.FromMinutes(30))
                    };

                    await Microsoft.AspNetCore.Http.AuthenticationManagerExtensions.SignInAsync(HttpContext, findUser.SubjectId, findUser.Username, profiles);

                    return string.IsNullOrEmpty(returnUrl) ? Redirect("/home/index") : Redirect(returnUrl);
                }
                ModelState.AddModelError(nameof(loginModel.Password), "密码不正确");
            }
            return View();

        }

 

转载于:https://www.cnblogs.com/qinzb/p/9503303.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在Spring Boot 2.7及以上版本中,可以使用spring-boot-starter-oauth2-authorization-server-1.2来自定义配置OIDC(OpenID Connect)实例。OIDC是一种基于OAuth 2.0协议的身份验证和授权协议,它允许客户端应用程序通过认证服务器来验证用户的身份并获取访问令牌。 要自定义配置OIDC实例,你可以按照以下步骤进行操作: 1. 首先,在你的Spring Boot项目中添加spring-boot-starter-oauth2-authorization-server-1.2依赖。可以在项目的pom.xml文件中添加以下依赖项: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-oauth2-authorization-server</artifactId> <version>1.2.0</version> </dependency> ``` 2. 接下来,你需要创建一个配置类来定义OIDC实例的配置。可以创建一个类,并使用`@Configuration`注解标记它,然后使用`@EnableAuthorizationServer`注解启用授权服务器功能。在配置类中,你可以使用`@Bean`注解来定义各种组件和配置。 ```java @Configuration @EnableAuthorizationServer public class OIDCConfig extends AuthorizationServerConfigurerAdapter { // 在这里定义你的OIDC实例的配置 } ``` 3. 在OIDCConfig类中,你可以重写`configure(ClientDetailsServiceConfigurer clients)`方法来配置客户端详细信息。可以使用`clients.inMemory()`方法来配置内存中的客户端信息,也可以使用`clients.jdbc(dataSource)`方法来配置数据库中的客户端信息。 ```java @Override public void configure(ClientDetailsServiceConfigurer clients) throws Exception { clients.inMemory() .withClient("client-id") .secret("client-secret") .authorizedGrantTypes("authorization_code", "refresh_token") .scopes("openid") .redirectUris("http://localhost:8080/callback"); } ``` 4. 此外,你还可以根据需要重写其他方法来自定义OIDC实例的配置,例如`configure(AuthorizationServerSecurityConfigurer security)`方法用于配置授权服务器的安全性,`configure(AuthorizationServerEndpointsConfigurer endpoints)`方法用于配置授权服务器的端点等。 至此,你已经完成了自定义配置OIDC实例的步骤。你可以根据具体需求进行更多的配置和定制化。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值