鍍金池/ 問答/Java  網(wǎng)絡安全/ spring-security 結合jwt 是使用用戶名密碼,可是實際項目中是使

spring-security 結合jwt 是使用用戶名密碼,可是實際項目中是使用手機號驗證登錄的,如何解決?

1、項目中使用的是spring-security+jwt根據(jù)用戶名和密碼來生成token,可是實際項目尤其是移動端是使用手機號來做驗證的,這個 如何解決?
2、如何在注冊 的時候就做登錄操作,也就是說之前是登錄才返回token,現(xiàn)在想在注冊的時候就返回token如何實現(xiàn)?

package com.qtay.gls.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.qtay.gls.dao.entity.User;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;

import static com.qtay.gls.auth.SecurityConstants.SECRET;

public class JWTLoginFilter extends UsernamePasswordAuthenticationFilter {

    private AuthenticationManager authenticationManager;

    public JWTLoginFilter(AuthenticationManager authenticationManager) {
        this.authenticationManager = authenticationManager;
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest req,
                                                HttpServletResponse res) throws AuthenticationException {
        try {
            User user = new ObjectMapper()
                    .readValue(req.getInputStream(), User.class);
            return authenticationManager.authenticate(
                    new UsernamePasswordAuthenticationToken(
                            user.getUsername(),
                            user.getPassword(),
                            new ArrayList<>())
            );
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    protected void successfulAuthentication(HttpServletRequest req,
                                            HttpServletResponse res,
                                            FilterChain chain,
                                            Authentication auth) throws IOException, ServletException {

        String token = Jwts.builder()
                .setSubject(((org.springframework.security.core.userdetails.User) auth.getPrincipal()).getUsername())
                .setExpiration(new Date(System.currentTimeMillis() + 60 * 60 * 24 * 1000))
                .signWith(SignatureAlgorithm.HS512, SECRET)
                .compact();
        res.addHeader("Authorization", "Bearer " + token);
    }
}
回答
編輯回答
檸檬藍

1.生成token的claim可以用手機號碼,填寫username也用手機號碼,解析的時候提取出手機號碼來驗證
2.注冊的時候可以返回吧,注冊的路由下返回的信息攜帶一個Token類,將生成的access_token和refresh_token一同返回就ok了。

2017年7月4日 15:39