首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >带凭据安全性的Spring令牌安全性(springboot)

问带凭据安全性的Spring令牌安全性(springboot)
EN

Stack Overflow用户
提问于 2017-06-02 01:42:02
回答 1查看 1.4K关注 0票数 4

关于服务器上的安全实现,我有一个问题。我正在制作一个SpringBoot应用程序,该应用程序上有一个控制面板,比如网站,其中只有一个管理输入需要数据,我已经设法保护了这个部分,就像这样:

代码语言:javascript
复制
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {




  @Override
  protected void configure(HttpSecurity http) throws Exception {


      http.antMatcher("/*").authorizeRequests().anyRequest().hasRole("ADMIN")
        .and().formLogin().loginPage("/login.jsp")
        .failureUrl("/login.jsp?error=1").loginProcessingUrl("/login")
        .permitAll().and().logout()
        .logoutSuccessUrl("/login.jsp");

  }

  @Override
  protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    // Create a default account
    auth.inMemoryAuthentication()
        .withUser("admin")
        .password("admin")
        .roles("ADMIN");
  }

每个网站的网址都在/*上,这很好。接下来我需要做的就是从我的移动应用程序中检索数据,并且它必须是安全的。应用程序应该使用的urls是/rest/**。我有一个学生类,存储电子邮件(用户名)和密码,这是由管理员在网站上创建的。据我所知,我需要令牌实现。

如何实现令牌身份验证?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-06-02 02:04:27

为移动应用程序实现基于令牌的身份验证,使用Spring和Security。

创建一个TokenAuthenticationFilter

代码语言:javascript
复制
public class TokenAuthenticationFilter extends GenericFilterBean {

    private AuthenticationManager authenticationManager;

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

    @Override
    public void doFilter(ServletRequest request,
                                             ServletResponse response,
                                             FilterChain chain) throws IOException, ServletException {

        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;

        String apiKey = httpRequest.getHeader("API-Key");
        String token = httpRequest.getHeader("Access-Token");

        try {
            if (!StringUtils.isEmpty(apiKey)) {
                processTokenAuthentication(apiKey);
            }
            chain.doFilter(request, response);
        } catch (InternalAuthenticationServiceException internalAuthenticationServiceException)
        {
            SecurityContextHolder.clearContext();
            logger.error("Internal authentication service exception", internalAuthenticationServiceException);
            httpResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
            catch(AuthenticationException authenticationException)
        {
            SecurityContextHolder.clearContext();
            httpResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED, authenticationException.getMessage());
        }
    }

    private void processTokenAuthentication(String apiKey) {
        SessionCredentials authCredentials = new SessionCredentials(apiKey);
        Authentication requestAuthentication = new PreAuthenticatedAuthenticationToken(authCredentials, authCredentials);
        Authentication resultOfAuthentication = tryToAuthenticate(requestAuthentication);
        SecurityContextHolder.getContext().setAuthentication(resultOfAuthentication);
    }

    private Authentication tryToAuthenticate(Authentication requestAuthentication) {
        Authentication responseAuthentication = authenticationManager.authenticate(requestAuthentication);
        if (responseAuthentication == null || !responseAuthentication.isAuthenticated()) {
            throw new InternalAuthenticationServiceException("Unable to authenticate Domain User for provided credentials");
        }
        return responseAuthentication;
    }
}

public class TokenAuthenticationProvider implements AuthenticationProvider {

    private String apiKey;

    public TokenAuthenticationProvider(String apiKey) {
        this.apiKey = apiKey;
    }

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        SessionCredentials credentials = (SessionCredentials) authentication.getCredentials();
        if (credentials != null && credentials.apiKey.equals(this.apiKey)) {

            //Also evaluate the token here

            Authentication newAuthentication = new PreAuthenticatedAuthenticationToken(apiKey, credentials);
            newAuthentication.setAuthenticated(true);
            return newAuthentication;
        }
        throw new BadCredentialsException("Bad credentials given.");
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return aClass.equals(PreAuthenticatedAuthenticationToken.class);
    }
}

创建会话凭据持有人

代码语言:javascript
复制
public class SessionCredentials {

    String apiKey;
    String accessToken;

    public SessionCredentials(String apiKey, String accessToken) {
        this.apiKey = apiKey;
        this.accessToken = accessToken;
    }

    public String getApiKey() {
        return apiKey;
    }

    public String getAccessToken() {
        return accessToken;
    }
}

最后在您的安全Config中注册这些

代码语言:javascript
复制
//Leave whatever you had here
@Override
public void configure(HttpSecurity http) throws Exception {
    http.addFilterBefore(new TokenAuthenticationFilter(authenticationManager()), BasicAuthenticationFilter.class);

    String contentPathDir = String.format("/%s/**", contentPath);

    http.csrf().disable()
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
            .and().authorizeRequests()
            .antMatchers("/authorization/**", "/public/**", "/management/**", "/health/**", contentPathDir).permitAll()
            .antMatchers("/**").authenticated();
}




//Add these two below. 
@Override
public void configure(AuthenticationManagerBuilder auth) {
    auth.authenticationProvider(apiKeyAuthenticationProvider());
}

@Bean
public TokenAuthenticationProvider apiKeyAuthenticationProvider() {
    return new TokenAuthenticationProvider(apiKey);
}
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/44319571

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档