【Spring Security OAuth开发APP认证框架】--- 将用户名密码登陆嫁接到Spring Security OAuth


项目源码地址 https://github.com/nieandsun/security


1 将自定义认证方式嫁接到Spring Security OAuth的原理

上篇文章《【Spring Security OAuth】— 获取token核心源码解读》比较细致的解读了Spring Security OAuth生成token的核心源码,其主要流程如下图:
在这里插入图片描述
而我们的目标是将Spring Security OAuth默认的走授权流程后发放token的步骤替换成走我们自定义的认证方式后发放token。既然要在我们自定义的认证方式认证成功后才发放token,则我们发放token的代码应该写在认证成功处理器里,回看上图联系其源码,可以知道:

(1)ClientDetails是通过请求头中的client-id获得的
(2)TokenRequest对象是通过请求参数+ClientDetails对象new出来的
(3)第④步是真正与授权模式相关的
(4)走完第④步会生成两个对象OAuth2Request和Authentication,而OAuth2Request是对ClientDetails对象和TokenRequest对象的封装Authentication对象即授权用户的对象 — 走完我们自定义的认证方式其实就会获得一个Authentication对象,因此在我们将自定义的认证方式嫁接到Spring Security OAuth框架的过程中不需要考虑该对象
(5)获得了OAuth2Reques和tAuthentication对象可以直接new 出一个OAuth2Authentication对象
(6)有了OAuth2Authentication对象我们就可以调用Spring Security OAuth默认的获取token的方法了

参照上面的步骤将我们自定义的认证方式嫁接到Spring Security OAuth的大致流程如下:
在这里插入图片描述

2 将用户名密码登陆嫁接到Spring Security OAuth

2.1 认证成功处理器 — 认证成功后生成token

package com.nrsc.security.app.authentication;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.nrsc.security.core.properties.NrscSecurityProperties;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.security.SecurityProperties;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.Authentication;
import org.springframework.security.crypto.codec.Base64;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.common.exceptions.UnapprovedClientAuthenticationException;
import org.springframework.security.oauth2.provider.*;
import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created By: Sun Chuan
 * Created Date: 2019/6/18 19:32
 */
@Slf4j
@Component(value = "NRSCAuthenticationSuccessHandler")
public class NRSCAuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {

    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private SecurityProperties securityProperties;

    @Autowired
    private ClientDetailsService clientDetailsService;

    @Autowired
    private AuthorizationServerTokenServices authorizationServerTokenServices;
    @Autowired
    private NrscSecurityProperties nrscSecurityProperties;

    /**
     * Authentication封装了用户认证成功的信息
     */
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
                                        Authentication authentication) throws IOException, ServletException {

        logger.info("登录成功");
        //请求头的Authorization里存放了ClientId和ClientSecret
        //从请求头里获取Authorization信息可参考BasicAuthenticationFilter类
        String header = request.getHeader("Authorization");

        if (header == null || !header.startsWith("Basic ")) {
            throw new UnapprovedClientAuthenticationException("请求头中无client信息");
        }

        String[] tokens = extractAndDecodeHeader(header, request);
        assert tokens.length == 2;

        String clientId = tokens[0];
        String clientSecret = tokens[1];

        // 根据clientId获取ClientDetails对象 --- ClientDetails为第三方应用的信息
        // 现在配置在了yml文件里,真实项目中应该放在数据库里
        ClientDetails clientDetails = clientDetailsService.loadClientByClientId(clientId);

        // 对获取到的clientDetails进行校验
        if (clientDetails == null) {
            throw new UnapprovedClientAuthenticationException("clientId对应的配置信息不存在:" + clientId);
        } else if (!StringUtils.equals(clientDetails.getClientSecret(), clientSecret)) {
            throw new UnapprovedClientAuthenticationException("clientSecret不匹配:" + clientId);
        }

        //第一个参数为请求参数的一个Map集合,
        // 在Spring Security OAuth的源码里要用这个Map里的用户名+密码或授权码来生成Authentication对象,
        // 但我们已经获取到了Authentication对象,所以这里可以直接传一个空的Map
        //第三个参数为scope即请求的权限 ---》这里的策略是获得的ClientDetails对象里配了什么权限就给什么权限 //todo
        //第四个参数为指定什么模式 比如密码模式为password,授权码模式为authorization_code,
        // 这里我们写一个自定义模式custom
        TokenRequest tokenRequest = new TokenRequest(MapUtils.EMPTY_MAP, 
        clientId, clientDetails.getScope(), "custom");

        //获取OAuth2Request对象
        //源码中是这么写的 --- todo 有兴趣的可以看一下
        // OAuth2Request storedOAuth2Request = getRequestFactory().createOAuth2Request(client, tokenRequest);
        OAuth2Request oAuth2Request = tokenRequest.createOAuth2Request(clientDetails);

        //new出一个OAuth2Authentication对象
        OAuth2Authentication oAuth2Authentication = new OAuth2Authentication(oAuth2Request, authentication);

        //生成token
        OAuth2AccessToken token = authorizationServerTokenServices.createAccessToken(oAuth2Authentication);
		//将生成的token返回
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().write(objectMapper.writeValueAsString(token));
    }

    /**
     * 从header获取Authentication信息 --- 》 clientId和clientSecret
     * @param header
     * @param request
     * @return
     * @throws IOException
     */
    private String[] extractAndDecodeHeader(String header, HttpServletRequest request) throws IOException {

        byte[] base64Token = header.substring(6).getBytes("UTF-8");
        byte[] decoded;
        try {
            decoded = Base64.decode(base64Token);
        } catch (IllegalArgumentException e) {
            throw new BadCredentialsException("Failed to decode basic authentication token");
        }
        String token = new String(decoded, "UTF-8");
        int delim = token.indexOf(":");

        if (delim == -1) {
            throw new BadCredentialsException("Invalid basic authentication token");
        }
        return new String[]{token.substring(0, delim), token.substring(delim + 1)};
    }
}

2.2 app模块加入安全配置信息 — 让我们自定义的认证方式生效

package com.nrsc.security.app;

import com.nrsc.security.core.authentication.mobile.SmsCodeAuthenticationSecurityConfig;
import com.nrsc.security.core.properties.NrscSecurityProperties;
import com.nrsc.security.core.properties.SecurityConstants;
import com.nrsc.security.core.social.SocialConfig;
import com.nrsc.security.core.validate.code.ValidateCodeSecurityConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.social.security.SpringSocialConfigurer;

/**
 * @author : Sun Chuan
 * @date : 2019/10/15 10:57
 * Description: 资源服务器
 */
@Configuration
@EnableResourceServer
public class NrscResourcesServerConfig  extends ResourceServerConfigurerAdapter {

    @Autowired
    protected AuthenticationSuccessHandler NRSCAuthenticationSuccessHandler;

    @Autowired
    protected AuthenticationFailureHandler NRSCAuthenticationFailureHandler;

    @Autowired
    private SmsCodeAuthenticationSecurityConfig smsCodeAuthenticationSecurityConfig;

    @Autowired
    private ValidateCodeSecurityConfig validateCodeSecurityConfig;

    /**
     * @see SocialConfig#nrscSocialSecurityConfig()
     */
    @Autowired
    private SpringSocialConfigurer nrscSocialSecurityConfig;


    @Autowired
    private NrscSecurityProperties nrscSecurityProperties;

    @Override
    public void configure(HttpSecurity http) throws Exception {

        http.formLogin()
                .loginPage(SecurityConstants.DEFAULT_UNAUTHENTICATION_URL)
                .loginProcessingUrl(SecurityConstants.DEFAULT_LOGIN_PROCESSING_URL_FORM)
                .successHandler(NRSCAuthenticationSuccessHandler)
                .failureHandler(NRSCAuthenticationFailureHandler);
        
        //验证码有一些问题:因为验证码会放到session里,校验也需要从session里取,
        // 但是在token认证的情景下是不需session参与的
        // 所以这里先注释掉,下篇文章再解决
        http//.apply(validateCodeSecurityConfig) 
                //	.and()
                .apply(smsCodeAuthenticationSecurityConfig)
                .and()
                .apply(nrscSocialSecurityConfig)
                .and()
                .authorizeRequests()
                .antMatchers(
                        SecurityConstants.DEFAULT_UNAUTHENTICATION_URL,
                        SecurityConstants.DEFAULT_LOGIN_PROCESSING_URL_MOBILE,
                        nrscSecurityProperties.getBrowser().getLoginPage(),
                        SecurityConstants.DEFAULT_VALIDATE_CODE_URL_PREFIX+"/*",
                        nrscSecurityProperties.getBrowser().getSignUpUrl(),
                        nrscSecurityProperties.getBrowser().getSession().getSessionInvalidUrl(),
                        nrscSecurityProperties.getBrowser().getSignOutUrl(),
                        "/user/regist")
                .permitAll()
                .anyRequest()
                .authenticated()
                .and()
                .csrf().disable();
    }
}

3 测试

(1) 登陆测试

发送的登陆请求为POST请求,路径为http://127.0.0.1:8080/authentication/form ,同时需要再请求头里加上Client-Id和Client-Secret,请求参数为username和password
可以看到已经获取到了token信息
在这里插入图片描述

(2) 拿着刚才生成的token请求资源服务器的接口

可以看到已经获取到了用户信息
在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值