Springboot通过Controller

时间:2018-03-28 08:36:49

标签: java spring spring-boot spring-security jwt

问题: 我想从authenticate.getName()获取/提取用户名/电子邮件...如果可能,不要使用解析字符串。

authentication.getName()或principal.getName()值:

[username]: org.springframework.security.core.userdetails.User@21463e7a: Username: butitoy@iyotbihagay.com; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; Not granted any authorities

在这个例子中,我只想获得Username的值,即butitoy@iyotbihagay.com

解决方案:

由于我只想获取用户名/电子邮件(butitoy@iyotbihagay.com),并且它返回了整个主要内容/文本(上图),我从主要值中替换了我在主题中设置的值。 。到电子邮件价值..现在可以使用了。

@Override
protected void successfulAuthentication(HttpServletRequest req,
                                        HttpServletResponse res,
                                        FilterChain chain,
                                        Authentication auth) throws IOException, ServletException {
    String email = auth.getName();
    String principal = auth.getPrincipal().toString();
    Date expiration = new Date(System.currentTimeMillis() + SecurityConstants.EXPIRATION_TIME);
    String token = Jwts.builder()
            .setSubject(email) //from principal to email
            .setExpiration(expiration)
            .signWith(SignatureAlgorithm.HS512, SecurityConstants.SECRET.getBytes())
            .compact();
    AuthenticatedUser loginUser = new AuthenticatedUser(email);
    loginUser.setToken(token);
    String jsonUser = Util.objectToJsonResponseAsString(loginUser, "user");
    res.addHeader(SecurityConstants.HEADER_STRING, SecurityConstants.TOKEN_PREFIX + token);
    res.setContentType("application/json");
    res.setCharacterEncoding(ConstantUtil.DEFAULT_ENCODING);
    res.getWriter().write(jsonUser);
}

我现在可以使用不同的方式获取用户名/电子邮件值,就像你们建议的那样......甚至是我目前使用的那个。我现在不需要任何特殊的解析来获取Authentication对象的电子邮件值。

在我之前使用Spring的非RESTful应用程序...我可以使用在控制器方法参数中注入的Authentication类轻松获取用户名。

控制器:

...  
public Ticket getBySwertresNo(Authentication authentication, @PathVariable String swertresNo) {  
    logger.debug("Inside getBySwertresNo: " + swertresNo);  
    System.out.println("\n[username]: " + authentication.getName() + "\n");  
    return m_sugalService.getSwertresInfoBySwertresNo(swertresNo);  
}  
...  

控制台:

[username]: butitoy@iyotbihagay.com

现在,在我当前的项目中......我使用了RESTful方法,在成功进行身份验证后,我将返回一个将在请求标头中使用/注入的令牌。我可以使用令牌登录...但是当我获得authentication.getName()的值时...返回不仅仅是电子邮件地址,还包含一些其他信息。

控制台(REST + JWT):

[username]: org.springframework.security.core.userdetails.User@21463e7a: Username: butitoy@iyotbihagay.com; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; Not granted any authorities

我想只获取用户名值" butitoy@iyotbihagay.com"。

JWT身份验证过滤器:

public class JWTAuthenticationFilter extends UsernamePasswordAuthenticationFilter {

    private AuthenticationManager authenticationManager;

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

    @Override
    public Authentication attemptAuthentication(HttpServletRequest req,
                                                HttpServletResponse res) throws AuthenticationException {
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, password);
        Authentication authentication = authenticationManager.authenticate(authenticationToken);
        return authentication;
    }

    @Override
    protected void successfulAuthentication(HttpServletRequest req,
                                            HttpServletResponse res,
                                            FilterChain chain,
                                            Authentication auth) throws IOException, ServletException {
        String email = auth.getName();
        String principal = auth.getPrincipal().toString();
        Date expiration = new Date(System.currentTimeMillis() + SecurityConstants.EXPIRATION_TIME);
        String token = Jwts.builder()
                .setSubject(principal)
                .setExpiration(expiration)
                .signWith(SignatureAlgorithm.HS512, SecurityConstants.SECRET.getBytes())
                .compact();
        AuthenticatedUser loginUser = new AuthenticatedUser(email);
        loginUser.setToken(token);
        String jsonUser = Util.objectToJsonResponseAsString(loginUser, "user");
        res.addHeader(SecurityConstants.HEADER_STRING, SecurityConstants.TOKEN_PREFIX + token);
        res.setContentType("application/json");
        res.setCharacterEncoding(ConstantUtil.DEFAULT_ENCODING);
        res.getWriter().write(jsonUser);
    }

}

JWT授权过滤器:

public class JWTAuthorizationFilter extends BasicAuthenticationFilter {

    public JWTAuthorizationFilter(AuthenticationManager authManager) {
        super(authManager);
    }

    @Override
    protected void doFilterInternal(HttpServletRequest req,
                                    HttpServletResponse res,
                                    FilterChain chain) throws IOException, ServletException {
        String header = req.getHeader(SecurityConstants.HEADER_STRING);

        if (header == null || !header.startsWith(SecurityConstants.TOKEN_PREFIX)) {
            chain.doFilter(req, res);
            return;
        }

        UsernamePasswordAuthenticationToken authentication = getAuthentication(req);

SecurityContextHolder.getContext().setAuthentication(authentication);
        chain.doFilter(req, res);
    }

    private UsernamePasswordAuthenticationToken getAuthentication(HttpServletRequest request) {
        String token = request.getHeader(SecurityConstants.HEADER_STRING);
        if (token != null) {
            // parse the token.
            String user = Jwts.parser()
                    .setSigningKey(SecurityConstants.SECRET.getBytes())
                    .parseClaimsJws(token.replace(SecurityConstants.TOKEN_PREFIX, ""))
                    .getBody()
                    .getSubject();

            if (user != null) {
                return new UsernamePasswordAuthenticationToken(user, null, new ArrayList<>());
            }
            return null;
        }
        return null;
    }

}

4 个答案:

答案 0 :(得分:5)

我认为您可以在authentication.getNameprincipal.getName类型的注入控制器参数中使用AuthenticationPrincipal

@Controller
@RequestMapping("/info")
public class GetNameController {

    @RequestMapping(value = "/name", method = RequestMethod.GET)
    public String getName(Authentication authentication, Principal principal) {
        System.out.println(authentication.getName());
        System.out.println("-----------------");
        System.out.println(principal.getName());
        return "";
    }
}

可以产生

admin
-----------------
admin

答案 1 :(得分:3)

就Authentication / Principal对象而言,使用令牌或基本弹簧安全认证是否无关紧要。

如果是春季安全措施,您可以通过
获取当前登录用户 1. Object user = Authentication authentication(正如你已经在做的那样)
2.

Object user = SecurityContextHolder.getContext().getAuthentication()
                    .getPrincipal();

在这两种情况下,user都将包含您从UserDetailsService.loadUserByUsername(...)返回的用户对象。因此,使用默认UserDetailsService,您将获得Spring security的User对象,其中包含usernamepassword等基本用户信息。

如果您使用默认弹簧UserDetailsService,那么您可以通过

获取当前登录用户
UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext().getAuthentication()
                        .getPrincipal();
String username = userDetails.getUsername();

答案 2 :(得分:0)

您可以使用

  

导入org.springframework.security.core.Authentication;

     

导入org.springframework.security.core.context.SecurityContextHolder;

You can create a method in the activity, probably like

public void yourMethod() {

button.performClick();// you can access all the components present in your activity

}

Now create an instance of the activity in the fragment and access this method.

YourActivity activityInstance = (YourActivity) getActivity();

And then you can access the method using the isntance of the activity like

activityInstance.yourMethod();

答案 3 :(得分:0)

到目前为止尚未看到任何可接受的答案,也许这会有所帮助:

使用来自下课的JwtTokenUtils.debugPrint();调用。有关其他令牌有效负载,请参见tokenMap内部可用的内容。

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.jwt.Jwt;
import org.springframework.security.jwt.JwtHelper;
import org.springframework.security.oauth2.common.exceptions.InvalidTokenException;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.*;

import static org.springframework.security.oauth2.provider.token.AccessTokenConverter.EXP;

public class JwtTokenUtils {

    private static final Logger logger = LoggerFactory.getLogger(JwtTokenUtils.class);
    private static Format dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    private static ObjectMapper objectMapper = new ObjectMapper();

    public static void debugPrint() {
        try {
            Map<String, Object>  tokenMap = decode(getToken());
            logger.debug("JwtTokenUtils:debugPrint jwt:"
                    + " user_name {" + tokenMap.get("user_name")
                    + "}, expired {" + convertTime((long)tokenMap.get(EXP))
                    + "}");
        } catch (Exception e) {
            logger.error("JwtTokenUtils:debugPrint exception: " + e);
        }
    }

    private static String getToken() {
        return getAuthorizationHeader().split(" ")[1];
    }

    private static String getAuthorizationHeader() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
        return request.getHeader("Authorization");
    }

    private static Map<String, Object> decode(String token) {
        try {
            Jwt jwt = JwtHelper.decode(token);
            String claimsStr = jwt.getClaims();
            TypeReference<HashMap<String,Object>> typeRef = new TypeReference<>() {};
            return objectMapper.readValue(claimsStr, typeRef); 
        }
        catch (Exception e) {
            throw new InvalidTokenException("Cannot convert access token to JSON", e);
        }
    }

    private static String convertTime(long time){
        Date date = new Date(time * 1000);
        return dateFormat.format(date);
    }
}