国产xxxx99真实实拍_久久不雅视频_高清韩国a级特黄毛片_嗯老师别我我受不了了小说

資訊專欄INFORMATION COLUMN

Spring Security Oauth2.0 實現(xiàn)短信驗證碼登錄

陸斌 / 1118人閱讀

摘要:驗證碼的發(fā)放校驗邏輯比較簡單,方法后通過全局判斷請求中是否和手機號匹配集合,重點邏輯是令牌的參數(shù)

spring security oauth2 登錄過程詳解

?

?

定義手機號登錄令牌
/**
 * @author lengleng
 * @date 2018/1/9
 * 手機號登錄令牌
 */
public class MobileAuthenticationToken extends AbstractAuthenticationToken {

    private static final long serialVersionUID = SpringSecurityCoreVersion.SERIAL_VERSION_UID;

    private final Object principal;

    public MobileAuthenticationToken(String mobile) {
        super(null);
        this.principal = mobile;
        setAuthenticated(false);
    }

    public MobileAuthenticationToken(Object principal,
                                     Collection authorities) {
        super(authorities);
        this.principal = principal;
        super.setAuthenticated(true);
    }

    public Object getPrincipal() {
        return this.principal;
    }

    @Override
    public Object getCredentials() {
        return null;
    }

    public void setAuthenticated(boolean isAuthenticated) throws IllegalArgumentException {
        if (isAuthenticated) {
            throw new IllegalArgumentException(
                    "Cannot set this token to trusted - use constructor which takes a GrantedAuthority list instead");
        }

        super.setAuthenticated(false);
    }

    @Override
    public void eraseCredentials() {
        super.eraseCredentials();
    }
}
手機號登錄校驗邏輯
/**
 * @author lengleng
 * @date 2018/1/9
 * 手機號登錄校驗邏輯
 */
public class MobileAuthenticationProvider implements AuthenticationProvider {
    private UserService userService;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        MobileAuthenticationToken mobileAuthenticationToken = (MobileAuthenticationToken) authentication;
        UserVo userVo = userService.findUserByMobile((String) mobileAuthenticationToken.getPrincipal());

        UserDetailsImpl userDetails = buildUserDeatils(userVo);
        if (userDetails == null) {
            throw new InternalAuthenticationServiceException("手機號不存在:" + mobileAuthenticationToken.getPrincipal());
        }

        MobileAuthenticationToken authenticationToken = new MobileAuthenticationToken(userDetails, userDetails.getAuthorities());
        authenticationToken.setDetails(mobileAuthenticationToken.getDetails());
        return authenticationToken;
    }

    private UserDetailsImpl buildUserDeatils(UserVo userVo) {
        return new UserDetailsImpl(userVo);
    }

    @Override
    public boolean supports(Class authentication) {
        return MobileAuthenticationToken.class.isAssignableFrom(authentication);
    }

    public UserService getUserService() {
        return userService;
    }

    public void setUserService(UserService userService) {
        this.userService = userService;
    }
}
登錄過程filter處理
**
 * @author lengleng
 * @date 2018/1/9
 * 手機號登錄驗證filter
 */
public class MobileAuthenticationFilter extends AbstractAuthenticationProcessingFilter {
    public static final String SPRING_SECURITY_FORM_MOBILE_KEY = "mobile";

    private String mobileParameter = SPRING_SECURITY_FORM_MOBILE_KEY;
    private boolean postOnly = true;

    public MobileAuthenticationFilter() {
        super(new AntPathRequestMatcher(SecurityConstants.MOBILE_TOKEN_URL, "POST"));
    }

    public Authentication attemptAuthentication(HttpServletRequest request,
                                                HttpServletResponse response) throws AuthenticationException {
        if (postOnly && !request.getMethod().equals(HttpMethod.POST.name())) {
            throw new AuthenticationServiceException(
                    "Authentication method not supported: " + request.getMethod());
        }

        String mobile = obtainMobile(request);

        if (mobile == null) {
            mobile = "";
        }

        mobile = mobile.trim();

        MobileAuthenticationToken mobileAuthenticationToken = new MobileAuthenticationToken(mobile);

        setDetails(request, mobileAuthenticationToken);

        return this.getAuthenticationManager().authenticate(mobileAuthenticationToken);
    }

    protected String obtainMobile(HttpServletRequest request) {
        return request.getParameter(mobileParameter);
    }

    protected void setDetails(HttpServletRequest request,
                              MobileAuthenticationToken authRequest) {
        authRequest.setDetails(authenticationDetailsSource.buildDetails(request));
    }

    public void setPostOnly(boolean postOnly) {
        this.postOnly = postOnly;
    }

    public String getMobileParameter() {
        return mobileParameter;
    }

    public void setMobileParameter(String mobileParameter) {
        this.mobileParameter = mobileParameter;
    }

    public boolean isPostOnly() {
        return postOnly;
    }
}
生產(chǎn)token 位置
/**
 * @author lengleng
 * @date 2018/1/8
 * 手機號登錄成功,返回oauth token
 */
@Component
public class MobileLoginSuccessHandler implements org.springframework.security.web.authentication.AuthenticationSuccessHandler {
    private Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    private ObjectMapper objectMapper;
    @Autowired
    private ClientDetailsService clientDetailsService;
    @Autowired
    private AuthorizationServerTokenServices authorizationServerTokenServices;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
        String header = request.getHeader("Authorization");

        if (header == null || !header.startsWith("Basic ")) {
            throw new UnapprovedClientAuthenticationException("請求頭中client信息為空");
        }

        try {
            String[] tokens = extractAndDecodeHeader(header);
            assert tokens.length == 2;
            String clientId = tokens[0];
            String clientSecret = tokens[1];

            JSONObject params = new JSONObject();
            params.put("clientId", clientId);
            params.put("clientSecret", clientSecret);
            params.put("authentication", authentication);

            ClientDetails clientDetails = clientDetailsService.loadClientByClientId(clientId);
            TokenRequest tokenRequest = new TokenRequest(MapUtil.newHashMap(), clientId, clientDetails.getScope(), "mobile");
            OAuth2Request oAuth2Request = tokenRequest.createOAuth2Request(clientDetails);

            OAuth2Authentication oAuth2Authentication = new OAuth2Authentication(oAuth2Request, authentication);
            OAuth2AccessToken oAuth2AccessToken = authorizationServerTokenServices.createAccessToken(oAuth2Authentication);
            logger.info("獲取token 成功:{}", oAuth2AccessToken.getValue());

            response.setCharacterEncoding(CommonConstant.UTF8);
            response.setContentType(CommonConstant.CONTENT_TYPE);
            PrintWriter printWriter = response.getWriter();
            printWriter.append(objectMapper.writeValueAsString(oAuth2AccessToken));
        } catch (IOException e) {
            throw new BadCredentialsException(
                    "Failed to decode basic authentication token");
        }
    }

    /**
     * Decodes the header into a username and password.
     *
     * @throws BadCredentialsException if the Basic header is not present or is not valid
     *                                 Base64
     */
    private String[] extractAndDecodeHeader(String header)
            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, CommonConstant.UTF8);

        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)};
    }
}
配置以上自定義
//**
 * @author lengleng
 * @date 2018/1/9
 * 手機號登錄配置入口
 */
@Component
public class MobileSecurityConfigurer extends SecurityConfigurerAdapter {
    @Autowired
    private MobileLoginSuccessHandler mobileLoginSuccessHandler;
    @Autowired
    private UserService userService;

    @Override
    public void configure(HttpSecurity http) throws Exception {
        MobileAuthenticationFilter mobileAuthenticationFilter = new MobileAuthenticationFilter();
        mobileAuthenticationFilter.setAuthenticationManager(http.getSharedObject(AuthenticationManager.class));
        mobileAuthenticationFilter.setAuthenticationSuccessHandler(mobileLoginSuccessHandler);

        MobileAuthenticationProvider mobileAuthenticationProvider = new MobileAuthenticationProvider();
        mobileAuthenticationProvider.setUserService(userService);
        http.authenticationProvider(mobileAuthenticationProvider)
                .addFilterAfter(mobileAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
    }
}
在spring security 配置 上邊定一個的那個聚合配置
/**
 * @author lengleng
 * @date 2018年01月09日14:01:25
 * 認證服務(wù)器開放接口配置
 */
@Configuration
@EnableResourceServer
public class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {
    @Autowired
    private FilterUrlsPropertiesConifg filterUrlsPropertiesConifg;
    @Autowired
    private MobileSecurityConfigurer mobileSecurityConfigurer;

    @Override
    public void configure(HttpSecurity http) throws Exception {
        registry
                .antMatchers("/mobile/token").permissionAll()
                .anyRequest().authenticated()
                .and()
                .csrf().disable();
        http.apply(mobileSecurityConfigurer);
    }
}
使用
curl -H "Authorization:Basic cGlnOnBpZw==" -d "grant_type=mobile&scope=server&mobile=17034642119&code=" http://localhost:9999/auth/mobile/token
源碼

請參考 https://gitee.com/log4j/

基于Spring Cloud、Spring Security Oauth2.0開發(fā)企業(yè)級認證與授權(quán),提供常見服務(wù)監(jiān)控、鏈路追蹤、日志分析、緩存管理、任務(wù)調(diào)度等實現(xiàn)

整個邏輯是參考spring security 自身的 usernamepassword 登錄模式實現(xiàn),可以參考其源碼。

驗證碼的發(fā)放、校驗邏輯比較簡單,方法后通過全局fiter 判斷請求中code 是否和 手機號匹配集合,重點邏輯是令牌的參數(shù)

文章版權(quán)歸作者所有,未經(jīng)允許請勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。

轉(zhuǎn)載請注明本文地址:http://specialneedsforspecialkids.com/yun/68223.html

相關(guān)文章

  • Spring Security OAuth2 優(yōu)雅的集成短信驗證登錄以及第三方登錄

    摘要:前言基于做微服務(wù)架構(gòu)分布式系統(tǒng)時,作為認證的業(yè)內(nèi)標(biāo)準(zhǔn),也提供了全套的解決方案來支持在環(huán)境下使用,提供了開箱即用的組件。 前言 基于SpringCloud做微服務(wù)架構(gòu)分布式系統(tǒng)時,OAuth2.0作為認證的業(yè)內(nèi)標(biāo)準(zhǔn),Spring Security OAuth2也提供了全套的解決方案來支持在Spring Cloud/Spring Boot環(huán)境下使用OAuth2.0,提供了開箱即用的組件。但...

    yck 評論0 收藏0
  • 前后端分離項目 — 基于SpringSecurity OAuth2.0用戶認證

    摘要:前言現(xiàn)在的好多項目都是基于移動端以及前后端分離的項目,之前基于的前后端放到一起的項目已經(jīng)慢慢失寵并淡出我們視線,尤其是當(dāng)基于的微服務(wù)架構(gòu)以及單頁面應(yīng)用流行起來后,情況更甚。使用生成是什么請自行百度。 1、前言 現(xiàn)在的好多項目都是基于APP移動端以及前后端分離的項目,之前基于Session的前后端放到一起的項目已經(jīng)慢慢失寵并淡出我們視線,尤其是當(dāng)基于SpringCloud的微服務(wù)架構(gòu)以及...

    QLQ 評論0 收藏0
  • 前后端分離項目 — SpringSocial 綁定與解綁社交賬號如微信、QQ

    摘要:我們以微信為例,首先我們發(fā)送一個請求,因為你已經(jīng)登錄了,所以后臺可以獲取當(dāng)前是誰,然后就獲取到請求的鏈接,最后就是跳轉(zhuǎn)到這個鏈接上面去。 1、準(zhǔn)備工作 申請QQ、微信相關(guān)AppId和AppSecret,這些大家自己到QQ互聯(lián)和微信開發(fā)平臺 去申請吧 還有java后臺要引入相關(guān)的jar包,如下: org.springframework.security....

    tigerZH 評論0 收藏0
  • oauth 實現(xiàn)手機號登錄

    摘要:現(xiàn)在有一個需求就是改造實現(xiàn)手機號碼可以登錄需要重幾個類第一個類手機驗證碼登陸第二個類驗證碼驗證,調(diào)用公共服務(wù)查詢?yōu)榈模⑴袛嗥渑c驗證碼是否匹配第三個類第四個類第五個類不存在不匹配最后在配置一下設(shè)置禁止隱藏用戶未找到異常使用進行密碼 現(xiàn)在有一個需求就是改造 oauth2.0 實現(xiàn)手機號碼可以登錄 需要重幾個類 第一個類 public class PhoneLoginAuthenticat...

    hyuan 評論0 收藏0
  • 基于oauth 2.0 實現(xiàn)第三方開放平臺

    摘要:本文單純從簡單的技術(shù)實現(xiàn)來講,不涉及開放平臺的多維度的運營理念。它的特點就是通過客戶端的后臺服務(wù)器,與服務(wù)提供商的認證服務(wù)器進行互動能夠滿足絕大多數(shù)開放平臺認證授權(quán)的需求。 本文單純從簡單的技術(shù)實現(xiàn)來講,不涉及開放平臺的多維度的運營理念。 什么是開放平臺 通過開放自己平臺產(chǎn)品服務(wù)的各種API接口,讓其他第三方開發(fā)者在開發(fā)應(yīng)用時根據(jù)需求直接調(diào)用,例如微信登錄、QQ登錄、微信支付、微博登錄...

    Simon 評論0 收藏0

發(fā)表評論

0條評論

陸斌

|高級講師

TA的文章

閱讀更多
最新活動
閱讀需要支付1元查看
<