无法在spring-security的认证中获取自定义信息。

问题描述 投票:0回答:1

这是我 AuthenticationProvider 在授权服务器

@Service
public class UmUserAuthenticationProvider implements AuthenticationProvider {

    @Autowired
    @Qualifier("UmUserDetailsService")
    private UserDetailsService userDetailService;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        // TODO Auto-generated method stub

        String username = authentication.getName();
        String password = (String) authentication.getCredentials();

        long userId = (new SecurityUtil()).checkUser(umUserMapper, username, password);
        if (userId <= 0) {
            throw new BadCredentialsException("login failed");
        }
        UserDetails user = userDetailService.loadUserByUsername(username);

        //I've try different ways to put user detail in here
        UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(user, null,
                user.getAuthorities());
        auth.setDetails(user);
        return auth;
    }

    @Override
    public boolean supports(Class<?> authentication) {
        // TODO Auto-generated method stub
        return authentication.equals(UsernamePasswordAuthenticationToken.class);
    }

}

这是我的资源服务器,我无法获得我在 Authentication,

getPrincipalString

getDetails 是一种 org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationDetails

@RequestMapping("/test")
public class UserController {



    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @RequestMapping(value = "/test", method = RequestMethod.GET)
    public String getRouters() {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        logger.info(auth.getPrincipal().toString());
        logger.info(auth.getDetails().toString());


        JSONObject jo = new JSONObject();

        return jo.toString();
    }


记录仪打印enter image description here

所以猫我如何得到自定义的细节在 Authentication?

spring spring-boot spring-mvc spring-security spring-security-oauth2
1个回答
0
投票

最后,我用一个小技巧的方式解决了这个问题。

随我 UsernamePasswordAuthenticationToken,我得到的类型 String所以我用json字符串填充它。


UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(
                new JSONObject(user).toString(), password, userDetailService.getAuthorities(username));

所以我可以在控制器上解析json字符串。

但我还是想知道是什么原因导致它


0
投票

我认为问题在于,你把 UserDetails 但它已被默认值所覆盖。

一个自定义的认证转换器可能是解决方案。

public class CustomAuthenticationConverter implements Converter<Jwt, AbstractAuthenticationToken> {

    @Override
    public AbstractAuthenticationToken convert(@NotNull final Jwt jwt) {
        String username = jwt.getClaimAsString("username");
        UserDetails user = userDetailService.loadUserByUsername(username);
        return new UsernamePasswordAuthenticationToken (jwt, user, userDetailService.getAuthorities(username)));
    }

}
© www.soinside.com 2019 - 2024. All rights reserved.