当前位置: 首页 > 知识库问答 >
问题:

Spring Security令牌认证如何认证?

梅玉堂
2023-03-14
@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);
    }
}
@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);
    }
}
@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;
    }
}
@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();
    }
}
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();
    }
}

最后,我实现了UserDetailsService接口

@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);
    }
}

共有1个答案

海嘉赐
2023-03-14
{
    "username": "auser",
    "password": "password",
    "dbname": "data01"  
}
Bearer <token>
 类似资料:
  • 问题内容: 我正在编写一个想同时用作Web应用程序和API提供程序的nodejs应用程序。验证用户身份后,我想为该用户分配一个令牌,以用于后续请求。这对于Web应用程序的通行证非常有用,因为我只是在会话中使用令牌对用户进行序列化和反序列化。但是,在响应API请求时,没有用于设置存储会话信息的cookie。理想情况下,护照将在会话和请求正文中都寻找令牌。有什么方法可以配置通行证来完成此任务吗? 问题

  • 问题内容: 我已经阅读了《 Django Rest Framework指南》并完成了所有教程。一切似乎都有意义,并且按应有的方式工作。我得到了如上所述的基本身份验证和会话身份验证。 http://django-rest-framework.org/api-guide 但是,我在文档的令牌认证部分苦苦挣扎,它缺少或没有教程那么深入。 http://django-rest-framework.org/

  • 问题内容: 我试图允许用户使用他们的帐户通过单独的Web服务登录我的Flask应用。我可以联系此Web服务的api并接收安全令牌。如何使用此令牌对用户进行身份验证,以便他们可以访问受限视图? 我不需要将用户保存到我自己的数据库中。我只想验证他们的会话。我相信可以使用Flask- Security和@auth_token_required装饰器完成此操作,但是文档不是很详细,我不确定如何实现。 编辑

  • 我正在使用wordpress rest api的JWT认证插件进行api访问认证,但问题是< code > https://example . com/WP-JSON/jwt-auth/v1/token 正在生成不允许的错误。 例如,如果我尝试在postman中运行此url``https://example.com/wp-json/jwt-auth/v1/token`该API还需要身份验证,因为它

  • 我通过以下方式进行身份验证 首先,我通过以下方式对AWS进行身份验证 我刚刚发现我可以用下面的命令重新配置,但我很好奇这是否是处理它的正确方法,以及是否有任何其他AWS方法提供。