searchusermenu
  • 发布文章
  • 消息中心
点赞
收藏
评论
分享
原创

Spring Security 扩展登陆方式

2023-08-01 14:18:38
23
0

使用spring security扩展登录方式,需要自定义以下类:

AbstractTokenGranter

用于发放token。一般在认证通过后调用TokenEndpoint.postAccessToken,security框架会根据grant_type参数调用到此发放token的方法

public class MyTokenGranter extends AbstractTokenGranter {
    
    // 保存在数据库中的登录标识符,登陆参数grant_type 需带上此标志
    private static final String GRANT_TYPE = "custom";

    private AuthenticationProvider myAuthenticationProvider;

    public MyTokenGranter(AuthenticationProvider myAuthenticationProvider, AuthorizationServerTokenServices tokenServices, ClientDetailsService clientDetailsService, OAuth2RequestFactory requestFactory){
        this(tokenServices, clientDetailsService, requestFactory, "custom");
    }

    protected MyTokenGranter(AuthorizationServerTokenServices tokenServices, ClientDetailsService clientDetailsService, OAuth2RequestFactory requestFactory, String grantType) {
        super(tokenServices, clientDetailsService, requestFactory, grantType);
    }


    protected OAuth2Authentication getOAuth2Authentication(ClientDetails client, TokenRequest tokenRequest) {
         // 发放token
    }

}

 

AuthenticationProvider

用户认证登录的用户身份。

public class MyAuthenticationProvider implements AuthenticationProvider {

    // 返回数据库中用户信息的封装
    @Resource
    UserDetailsService userDetailsService;
    
    //核心方法,可以从数据库拿到数据则证明当前用户通过认证,将封装后的信息返回
    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        if(authentication.isAuthenticated()){
            return authentication;
        }
        
        //从传入的参数获取username
        String myUsername = (String) authentication.getPrincipal();
        // 获取封装后的用户信息
        User user = (User)userDetailsService.loadUserByUsername(username);
     
        //构造封装后的Token,后续传入Token发放接口
        MyAuthenticationToken myAuthenticationResult = new MyAuthenticationToken(user, user.getAuthorities());
        myAuthenticationResult.setDetails(authentication.getDetails());
        return myAuthenticationResult;
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return MyAuthenticationToken.class.isAssignableFrom(authentication);
    }
}

 

AbstractAuthenticationToken

public class MyAuthenticationToken extends UsernamePasswordAuthenticationToken {

    private static final long serialVersionUID = 1L;
    
    // 根据需要,传入用户验证身份所必须的信息
    public MyAuthenticationToken(Object principal){
        super(principal, "");
    }

    public MyAuthenticationToken(Object principal, Collection<? extends GrantedAuthority> authorities){
        super(principal, "", authorities);
    }
}

 

完成以下类的自定义后,需在AuthServerConfig 中添加配置,启用新配置

public class AuthServerConfig extends AuthorizationServerConfigurerAdapter {


    @Autowired
    public myAuthenticationProvider myAuthenticationProvider;

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {

        endpoints.tokenStore(tokenStore()).authenticationManager(authenticationManager);
        TokenEnhancerChain tokenEnhancerChain = new TokenEnhancerChain();
        tokenEnhancerChain.setTokenEnhancers(Arrays.asList(accessTokenConverter(), myTokenEnhancer));
        endpoints.tokenEnhancer(tokenEnhancerChain);

        //在原有的token granter的基础上添加自定义的TokenGranter
        List<TokenGranter> granterList = new ArrayList<>(Arrays.asList(endpoints.getTokenGranter()));
        granterList.add(new CtyunTokenGranter(ctyunAuthenticationProvider, endpoints.getTokenServices(), endpoints.getClientDetailsService(), endpoints.getOAuth2RequestFactory()));
        CompositeTokenGranter compositeTokenGranter = new CompositeTokenGranter(granterList);
        endpoints.tokenGranter(compositeTokenGranter);
    }

    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        security
                .passwordEncoder(passwordEncoder())
                .tokenKeyAccess("permitAll()")
                .checkTokenAccess("permitAll()")
                .allowFormAuthenticationForClients();
    }
}

 

在Controller中暴露登录接口,对用户登录逻辑进行处理和扩展

public class MyAuthController extends ExceptionResponseHandler {

    @GetMapping(value = "/mylogin")
    public SingleResponse login(@RequestParam String usercode, @RequestParam(required = false) String redirectUrl, HttpServletRequest request, HttpServletResponse response) throws Exception{
          // 获取并解析第三方登录的认证信息
          // 调用 Provider.authenticate() 认证此信息
          // 构造AbstractToken
          // 调用 TokenEndpoint.postAccessToken() 生成登录凭证
          // 返回登陆凭证
    }

}

 

到此,可以实现第三方登录方式的扩展。

0条评论
作者已关闭评论
c****7
3文章数
0粉丝数
c****7
3 文章 | 0 粉丝
c****7
3文章数
0粉丝数
c****7
3 文章 | 0 粉丝
原创

Spring Security 扩展登陆方式

2023-08-01 14:18:38
23
0

使用spring security扩展登录方式,需要自定义以下类:

AbstractTokenGranter

用于发放token。一般在认证通过后调用TokenEndpoint.postAccessToken,security框架会根据grant_type参数调用到此发放token的方法

public class MyTokenGranter extends AbstractTokenGranter {
    
    // 保存在数据库中的登录标识符,登陆参数grant_type 需带上此标志
    private static final String GRANT_TYPE = "custom";

    private AuthenticationProvider myAuthenticationProvider;

    public MyTokenGranter(AuthenticationProvider myAuthenticationProvider, AuthorizationServerTokenServices tokenServices, ClientDetailsService clientDetailsService, OAuth2RequestFactory requestFactory){
        this(tokenServices, clientDetailsService, requestFactory, "custom");
    }

    protected MyTokenGranter(AuthorizationServerTokenServices tokenServices, ClientDetailsService clientDetailsService, OAuth2RequestFactory requestFactory, String grantType) {
        super(tokenServices, clientDetailsService, requestFactory, grantType);
    }


    protected OAuth2Authentication getOAuth2Authentication(ClientDetails client, TokenRequest tokenRequest) {
         // 发放token
    }

}

 

AuthenticationProvider

用户认证登录的用户身份。

public class MyAuthenticationProvider implements AuthenticationProvider {

    // 返回数据库中用户信息的封装
    @Resource
    UserDetailsService userDetailsService;
    
    //核心方法,可以从数据库拿到数据则证明当前用户通过认证,将封装后的信息返回
    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        if(authentication.isAuthenticated()){
            return authentication;
        }
        
        //从传入的参数获取username
        String myUsername = (String) authentication.getPrincipal();
        // 获取封装后的用户信息
        User user = (User)userDetailsService.loadUserByUsername(username);
     
        //构造封装后的Token,后续传入Token发放接口
        MyAuthenticationToken myAuthenticationResult = new MyAuthenticationToken(user, user.getAuthorities());
        myAuthenticationResult.setDetails(authentication.getDetails());
        return myAuthenticationResult;
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return MyAuthenticationToken.class.isAssignableFrom(authentication);
    }
}

 

AbstractAuthenticationToken

public class MyAuthenticationToken extends UsernamePasswordAuthenticationToken {

    private static final long serialVersionUID = 1L;
    
    // 根据需要,传入用户验证身份所必须的信息
    public MyAuthenticationToken(Object principal){
        super(principal, "");
    }

    public MyAuthenticationToken(Object principal, Collection<? extends GrantedAuthority> authorities){
        super(principal, "", authorities);
    }
}

 

完成以下类的自定义后,需在AuthServerConfig 中添加配置,启用新配置

public class AuthServerConfig extends AuthorizationServerConfigurerAdapter {


    @Autowired
    public myAuthenticationProvider myAuthenticationProvider;

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {

        endpoints.tokenStore(tokenStore()).authenticationManager(authenticationManager);
        TokenEnhancerChain tokenEnhancerChain = new TokenEnhancerChain();
        tokenEnhancerChain.setTokenEnhancers(Arrays.asList(accessTokenConverter(), myTokenEnhancer));
        endpoints.tokenEnhancer(tokenEnhancerChain);

        //在原有的token granter的基础上添加自定义的TokenGranter
        List<TokenGranter> granterList = new ArrayList<>(Arrays.asList(endpoints.getTokenGranter()));
        granterList.add(new CtyunTokenGranter(ctyunAuthenticationProvider, endpoints.getTokenServices(), endpoints.getClientDetailsService(), endpoints.getOAuth2RequestFactory()));
        CompositeTokenGranter compositeTokenGranter = new CompositeTokenGranter(granterList);
        endpoints.tokenGranter(compositeTokenGranter);
    }

    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        security
                .passwordEncoder(passwordEncoder())
                .tokenKeyAccess("permitAll()")
                .checkTokenAccess("permitAll()")
                .allowFormAuthenticationForClients();
    }
}

 

在Controller中暴露登录接口,对用户登录逻辑进行处理和扩展

public class MyAuthController extends ExceptionResponseHandler {

    @GetMapping(value = "/mylogin")
    public SingleResponse login(@RequestParam String usercode, @RequestParam(required = false) String redirectUrl, HttpServletRequest request, HttpServletResponse response) throws Exception{
          // 获取并解析第三方登录的认证信息
          // 调用 Provider.authenticate() 认证此信息
          // 构造AbstractToken
          // 调用 TokenEndpoint.postAccessToken() 生成登录凭证
          // 返回登陆凭证
    }

}

 

到此,可以实现第三方登录方式的扩展。

文章来自个人专栏
文章 | 订阅
0条评论
作者已关闭评论
作者已关闭评论
0
0