【发布时间】:2020-04-18 22:12:16
【问题描述】:
我正在使用 Spring 启动。
我正在使用我自己的身份验证服务器来验证我的用户。
所以在调用我的身份验证服务器后,我的结果是 UserInfo 类的 json。
如何在安全上下文中设置它?
我将我的班级视为与org.springframework.security.core.userdetails.User 和org.springframework.security.core.userdetails.UserDetails 不同的班级类型。
这是我的JwtAuthenticationFilter 课程。
@Component
public class JwtAuthenticationFilter extends OncePerRequestFilter {
@Autowired
private AuthenticationService authenticationService;
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
getJwtFromRequest(request, response, filterChain);
}
private void getJwtFromRequest(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
String bearerToken = request.getHeader("Authorization");
if (!StringUtils.hasText(bearerToken) || !bearerToken.startsWith("Bearer ")) {
throw new AccessTokenMissingException("No access token found in request headers");
}
// Call auth server to validate token
try {
ResponseEntity<String> result = authenticationService.getUserInfo(bearerToken.substring(7));
UserInfo user = new ObjectMapper().readValue(result.getBody(), UserInfo.class);
System.out.println(user.toString());
// Invalid access token
if (!result.getStatusCode().is2xxSuccessful()) {
throw new InvalidAccessTokenException("Invalid access token");
}
} catch (HttpClientErrorException.Unauthorized | IOException e) {
throw new InvalidAccessTokenException("Invalid access token");
}
//add to security context
filterChain.doFilter(request, response);
}
}
这是我的UserInfo 课程。
@Getter
@Setter
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class UserInfo implements Serializable {
private List<String> role = new ArrayList<>();
private String username
private String email;
}
【问题讨论】:
标签: spring-boot authentication spring-security