Java Spring Boot基本身份验证与Redis

时间:2018-10-21 21:28:17

标签: java spring spring-boot spring-security basic-authentication

我正在尝试将身份验证层添加到我的spring boot应用程序中,并且我可以找到的所有教程都是针对某个模拟用户的,例如:

@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
   auth.inMemoryAuthentication().withUser("learn").password("share").roles("USER");
}

我想实现这样的东西:

String credentials = request.getHeader('Authorization');
String userName = fetchUserName(credentials);
String password = fetchUserPassword(credentials);
String actualPassword = redis.getPassowrdForUser(userName);
if (actualPassword == someHash(password)) {
   // continue with the request
} else {
   // return unauthorised request 401
}

谢谢。


这是我目前的实现,来自我发现的一些教程:

@EnableWebSecurity
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private BasicAuthenticationPoint authEntryPoint;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable();
        http.authorizeRequests()
                .antMatchers("/user/signup").permitAll()
                .anyRequest().authenticated();

        http.httpBasic().authenticationEntryPoint(authEntryPoint);

        http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication().withUser("learn").password("share").roles("USER");
    }

    @Bean
    public static NoOpPasswordEncoder passwordEncoder() {
        return (NoOpPasswordEncoder) NoOpPasswordEncoder.getInstance();
    }
}



@Component
public class BasicAuthenticationPoint extends BasicAuthenticationEntryPoint {

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authEx)
            throws IOException, ServletException {
        response.addHeader("WWW-Authenticate", "Basic realm=" +getRealmName());
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        PrintWriter writer = response.getWriter();
        writer.println("HTTP Status 401 - " + authEx.getMessage());
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        setRealmName("learn");
        super.afterPropertiesSet();
    }

}

0 个答案:

没有答案