Spring Securty Rest登录

时间:2018-07-07 15:46:51

标签: java spring rest spring-security

我试图用api编写Web REST后端。现在,我可以对发送用户数据的任何请求进行授权,如下所示: enter image description here

但是我不喜欢这样,我只想使用一种资源进行授权/api/user/login

我有这个CustomWebSecurityConfigurerAdapter.java

@Configuration
@EnableWebSecurity
public class CustomWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {

    @Autowired
    private DataSource dataSource;

    @Autowired
    private AuthenticationEntryPoint authenticationEntryPoint;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.jdbcAuthentication().dataSource(dataSource)
                .usersByUsernameQuery(
                        "select username, password, true from users where username=?")
                .authoritiesByUsernameQuery(
                        "select username, role from users where username=?")
                .passwordEncoder(new BCryptPasswordEncoder());
    }

    @Override
    public void configure(WebSecurity web) {
        web.ignoring()
                .antMatchers("/api/test/getting")
                .antMatchers("/api/user/register")
                .antMatchers("/webjars/**")
                .antMatchers("/api/swagger-resources/configuration/ui")
                .antMatchers("/swagger-ui.html*");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                .anyRequest().authenticated()
                .and()
                .httpBasic()
                .authenticationEntryPoint(authenticationEntryPoint);
    }
}

你能解释一下它是如何工作的吗?

1 个答案:

答案 0 :(得分:0)

这是Spring Security的安全层。所有请求都必须经过它。

下一节将覆盖WebSecurityConfigurerAdapter中配置身份验证的方法
对于每个请求,除了少数几个网址(/api/test/getting/api/user/register/webjars/**/api/swagger-resources/configuration/ui/swagger-ui.html*)以外,因为在方法 { {1}}

所有请求都带有基本身份验证令牌(已加密),并且将从数据库表(用户和角色)中验证该值。如果用户凭证有效且具有有效的角色,则将转到下一步,否则将给出 401 HTTP响应。 在数据库选项卡中;必须通过

来编码和保存通行证
public void configure(WebSecurity web)

代码部分:

.passwordEncoder(new BCryptPasswordEncoder())

以下部分用于告诉应用程序所有请求都是HTTP请求,并且所有请求都必须通过基本身份验证@Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.jdbcAuthentication().dataSource(dataSource) .usersByUsernameQuery( "select username, password, true from users where username=?") .authoritiesByUsernameQuery( "select username, role from users where username=?") .passwordEncoder(new BCryptPasswordEncoder()); }

进行身份验证
.httpBasic()
相关问题