gpt4 book ai didi

java - Spring Security Token认证 如何认证?

转载 作者:行者123 更新时间:2023-12-02 04:34:59 26 4
gpt4 key购买 nike

我正在构建一个基于 Spring、Jersey、Spring Security 和 Tomcat 的 RESTful API。我发现这个教程看起来很棒,但它从未讨论如何实际验证用户身份,这似乎是一个主要部分( Stateless Authentication with Spring Security and JWT )

无论如何,我的实现都是基于此,现在我正在努力弄清楚如何进行身份验证并取回 token 。

我已经提供了我认为是下面所有相关代码的内容。现在的问题是我如何实际进行身份验证并取回 token ?

我尝试了这个,但我没有在响应 header 中返回 token 。

@Component
@Path("/auth")
@Produces(MediaType.APPLICATION_JSON)
public class AuthenticationEndPoint {

private UserSecurityService userService;

@Inject
public AuthenticationEndPoint(UserSecurityService userService) {
this.userService = userService;
}

@POST
public void doSomething(CredentialsDTO credentials) {
SecurityUser user = userService.loadUserByUsername(credentials.getUserName());
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(user.getUsername(),credentials.getPassword(),user.getAuthorities());
SecurityContextHolder.getContext().setAuthentication(token);
}
}

这是我的 Spring Security 配置

@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
@EnableWebSecurity
@Order(2)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

@Inject
private StatelessAuthenticationFilter statelessAuthenticationFilter;

@Inject
private UserSecurityService userSecurityService;

@Inject
public SecurityConfig() {
super(true);
}

@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
.exceptionHandling().and()
.anonymous().and()
.servletApi().and()
.headers().cacheControl().and()
.authorizeRequests()

// allow anonymous resource requests
.antMatchers("/").permitAll()
.antMatchers("/favicon.ico").permitAll()
.antMatchers("/public/**").permitAll()

// allow login
.antMatchers("/api/auth").permitAll()

// all other requests require authentication
.anyRequest().authenticated().and()

// token based authentication
.addFilterBefore(statelessAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
}

@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userSecurityService).passwordEncoder(bCryptPasswordEncoder());
}

@Bean
public BCryptPasswordEncoder bCryptPasswordEncoder() {
return new BCryptPasswordEncoder();
}

@Bean
public AuthenticationManager authenticationManager() throws Exception {
return super.authenticationManagerBean();
}
}

自定义用户:

public class SecurityUser extends User {

private org.company.app.domain.User user;

public SecurityUser(org.company.app.domain.User user,
Collection<GrantedAuthority> grantedAuthorities) {
super(user.getEmail(),user.getPasswordEncoded(),grantedAuthorities);
this.user = user;
}

public org.company.app.domain.User getUser() {
return user;
}

public void setUser(org.company.app.domain.User user) {
this.user = user;
}

public Collection<Role> getRoles() {
return this.user.getRoles();
}

@Override
public String toString() {
return MoreObjects.toStringHelper(this)
.add("user", user)
.toString();
}
}

过滤器:

@Service
public class StatelessAuthenticationFilter extends GenericFilterBean {

private final TokenAuthenticationService tokenAuthenticationService;

@Inject
public StatelessAuthenticationFilter(TokenAuthenticationService tokenAuthenticationService) {
this.tokenAuthenticationService = tokenAuthenticationService;
}

@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
FilterChain filterChain) throws IOException, ServletException {
Authentication authentication = tokenAuthenticationService.getAuthentication((HttpServletRequest) servletRequest);
SecurityContextHolder.getContext().setAuthentication(authentication);
filterChain.doFilter(servletRequest, servletResponse);
SecurityContextHolder.getContext().setAuthentication(null);
}
}

TokenAuthentication服务

@Service
public class TokenAuthenticationService {

private static final String AUTH_HEADER_NAME = "X-AUTH-TOKEN";

private final TokenHandler tokenHandler;

@Inject
public TokenAuthenticationService(TokenHandler tokenHandler) {
this.tokenHandler = tokenHandler;
}

public String addAuthentication(HttpServletResponse response, UserAuthentication authentication) {
final SecurityUser user = (SecurityUser) authentication.getDetails();
String token = tokenHandler.createTokenForUser(user);
response.addHeader(AUTH_HEADER_NAME, token);
return token;
}

public Authentication getAuthentication(HttpServletRequest request) {
final String token = request.getHeader(AUTH_HEADER_NAME);
if (token != null) {
final SecurityUser user = tokenHandler.parseUserFromToken(token);
if (user != null) {
return new UserAuthentication(user);
}
}
return null;
}
}

token 处理程序:

@Service
public class TokenHandler {

private Environment environment;
private final UserSecurityService userService;
private final String secret;

@Inject
public TokenHandler(Environment environment, UserSecurityService userService) {
this.environment = environment;
this.secret = this.environment.getRequiredProperty("application.security.secret");
this.userService = userService;
}

public SecurityUser parseUserFromToken(String token) {
String username = Jwts.parser()
.setSigningKey(secret)
.parseClaimsJws(token)
.getBody()
.getSubject();
return userService.loadUserByUsername(username);
}

public String createTokenForUser(SecurityUser user) {
return Jwts.builder()
.setSubject(user.getUsername())
.signWith(SignatureAlgorithm.HS512, secret)
.compact();
}
}

Spring Security Authentication接口(interface)的实现

public class UserAuthentication implements Authentication {

private final SecurityUser user;
private boolean authenticated = true;

public UserAuthentication(SecurityUser user) {
this.user = user;
}

@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return user.getAuthorities();
}

@Override
public Object getCredentials() {
return user.getPassword();
}

@Override
public Object getDetails() {
return user;
}

@Override
public Object getPrincipal() {
return user.getUsername();
}

@Override
public boolean isAuthenticated() {
return authenticated;
}

@Override
public void setAuthenticated(boolean b) throws IllegalArgumentException {
this.authenticated = b;
}

@Override
public String getName() {
return user.getUsername();
}
}

最后我实现了 UserDetailsS​​ervice 接口(interface)

@Service
public class UserSecurityService implements UserDetailsService {

private static final Logger logger = LoggerFactory.getLogger(UserSecurityService.class);

private UserService userService;

@Inject
public UserSecurityService(UserService userService) {
this.userService = userService;
}

private final AccountStatusUserDetailsChecker detailsChecker = new AccountStatusUserDetailsChecker();

@Override
public SecurityUser loadUserByUsername(String s) throws UsernameNotFoundException {

logger.debug("Attempting authentication with identifier {}", s);

User user = userService.getUserByUserName(s);
if (user == null) {
throw new UsernameNotFoundException(String.format("User with identifier %s was not found",s));
}

Collection<GrantedAuthority> authorities = new HashSet<>();
for (Role role : user.getRoles()) {
authorities.add(new SimpleGrantedAuthority(role.getSpringName()));
}

return new SecurityUser(user,authorities);
}
}

最佳答案

我们在项目中做了类似的事情。我们将 JWT token 作为响应正文的一部分发送。用 AngularJS 编写的客户端获取 token 并将其存储在浏览器内存中。然后,对于所有后续的安全调用,客户端将 token 作为承载 token 嵌入到请求 header 中。我们的身份验证 JSON 如下所示:

{
"username": "auser",
"password": "password",
"dbname": "data01"
}

对于每个常见的请求,我们在请求 header 中添加以下内容

Bearer <token>

关于java - Spring Security Token认证 如何认证?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33617815/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com