Spring Security REST登录

时间:2019-03-25 21:33:37

标签: spring rest api security login

我有关于使用带有Spring Security的REST API登录的问题。至于由Spring Security提供的使用默认登录窗口进行的登录正在运行并且正在通过数据库进行身份验证,我不知道如何进行自己的登录。我知道如何用表格代替自己的表格,但是我应该在哪里发送数据?我应该将其发布到某个地址吗?我用用户名和密码做了基本表格。

2 个答案:

答案 0 :(得分:0)

您可以将用户名和密码存储在数据库中,以用于登录用户。您创建自己的类,该类扩展了WebSecurityConfigurerAdapter并覆盖了您需要修改的方法:

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    DataSource dataSource;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception{
        auth.jdbcAuthentication()
            .dataSource(dataSource)
    }
}

但是在搜索用户名和密码时,请使用Spring Security默认数据库查询,以使您可以创建数据库架构,这会很好:

public static final String DEF_USERS_BY_USERNAME_QUERY =
"select username,password,enabled " +
"from users " +
"where username = ?";
public static final String DEF_AUTHORITIES_BY_USERNAME_QUERY =
"select username,authority " +
"from authorities " +
"where username = ?";
public static final String DEF_GROUP_AUTHORITIES_BY_USERNAME_QUERY =
"select g.id, g.group_name, ga.authority " +
"from groups g, group_members gm, group_authorities ga " +
"where gm.username = ? " +
"and g.id = ga.group_id " +
"and g.id = gm.group_id";

但是您也可以使用Spring方法来指定对数据库的查询:

auth
.jdbcAuthentication()
.dataSource(dataSource)
.usersByUsernameQuery(
"select username, password, enabled from Users " +
"where username=?")

您应该将数据发布到您创建的某些服务中,该服务将存储用户并传递给数据库。

答案 1 :(得分:0)

尝试这个,它可能对您有帮助...至少了解您所缺少的内容。 不能保证此代码可以100%正常工作,有意漏掉了某些部分(错误处理及其格式,加载用户,一些检查,会话API)。

基本思想是您必须注册一个筛选器(对所有受保护的身份验证请求进行响应)和提供者,该提供者以后将能够加载已认证的用户并为您创建安全上下文(例如,您知道每个请求都已处理)每个线程,可以通过SecurityContextHolder / ThreadLocal获取该用户。

您需要创建一个单独的控制器来处理创建用户会话(也称为登录/授权)的初始情况。此API的响应必须包含某个会话的GUID,才能稍后在Authentication: Bearer <value>

上将其用作标头值

一些规范:https://tools.ietf.org/html/rfc6750

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)//optional
@Import(RestSecurityConfig.TokenAuthenticationProvider.class)// one of the way to create spring bean
public class RestSecurityConfig extends WebSecurityConfigurerAdapter {
    private static final RequestMatcher PUBLIC_URLS = new OrRequestMatcher(
            new AntPathRequestMatcher("/actuator/*"),
            new AntPathRequestMatcher("/some_api_to_login", POST), // this must be public
    );
    private static final RequestMatcher PROTECTED_URLS = new NegatedRequestMatcher(PUBLIC_URLS);

    // better to move it out as a separate class
    public static class TokenAuthenticationProvider extends AbstractUserDetailsAuthenticationProvider {
        @Override
        public boolean supports(Class<?> authentication) {
            return MyAuthenticationToken.class.isAssignableFrom(authentication);
        }

        @Override
        protected void additionalAuthenticationChecks(UserDetails userDetails, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {

        }

        @Override
        protected UserDetails retrieveUser(String username, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {
            return null; // service/dao.loadUser
        }
    }

    public static class TokenAuthenticationFilter extends AbstractAuthenticationProcessingFilter {
        public TokenAuthenticationFilter(RequestMatcher requiresAuthenticationRequestMatcher) {
            super(requiresAuthenticationRequestMatcher);
        }

        @Override
        public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException {
            Authentication auth = new MyAuthenticationToken(request.getHeader("Authentication"));
            return getAuthenticationManager().authenticate(auth);
        }
    }

    @Autowired
    TokenAuthenticationProvider authenticationProvider;

    @Override
    protected void configure(final AuthenticationManagerBuilder auth) {
        auth.authenticationProvider(authenticationProvider);
    }

    @Override
    public void configure(final WebSecurity web) {
        web.ignoring().requestMatchers(PUBLIC_URLS);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // maybe some of the tuning you might not need
        http
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
                .exceptionHandling()
                .defaultAuthenticationEntryPointFor(new Http403ForbiddenEntryPoint(), PROTECTED_URLS).and()
                .authorizeRequests().anyRequest().authenticated().and()
                .cors().and()
                .anonymous().disable()
                .rememberMe().disable()
                .csrf().disable()
                .formLogin().disable()
                .httpBasic().disable()
                .logout().disable();

        // it's important
        http.addFilterBefore(tokenAuthenticationFilter(), AnonymousAuthenticationFilter.class);
    }

    @Bean
    AbstractAuthenticationProcessingFilter tokenAuthenticationFilter() throws Exception {
        final AbstractAuthenticationProcessingFilter filter = new TokenAuthenticationFilter(PROTECTED_URLS);
        filter.setAuthenticationManager(authenticationManager());
        filter.setAuthenticationSuccessHandler(successHandler());
        // maybe error handling to provide some custom response?
        return filter;
    }

    // it's critically important to register your filter properly in spring context
    /** Disable Spring boot automatic filter registration. */
    @Bean
    FilterRegistrationBean disableRegistrationForAuthenticationFilter(final TokenAuthenticationFilter filter) {
        final FilterRegistrationBean registration = new FilterRegistrationBean(filter);
        registration.setEnabled(false);
        return registration;
    }

    // this one also is critically important to avoid redirection
    @Bean
    SimpleUrlAuthenticationSuccessHandler successHandler() {
        final SimpleUrlAuthenticationSuccessHandler successHandler = new SimpleUrlAuthenticationSuccessHandler();
        successHandler.setRedirectStrategy(new NoRedirectStrategy());
        return successHandler;
    }

}
相关问题