如何在Spring Boot中创建自定义授权

时间:2018-09-05 09:01:12

标签: spring-boot spring-security

我想在所有对授权资源的请求都带有标头sessionId: uniqueSessionIdcharacters的spring-boot应用程序中使用自定义授权。放置检查逻辑的合适位置是什么?我要:

  • 具有一个可以访问标头并在我自己的数据库上执行select * from sessions的过滤器。
  • 如果此会话存在,它将调用下一个chain.filter,并将User(我)可以在@RestController中使用的请求注入
  • 如果不存在,则返回401。

会话

@Entity
public class Session {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    private String sessionId;

    @ManyToOne(fetch = FetchType.EAGER)
    @JoinColumn(name = "user_id", nullable = false)
    private User user;
}

WebSecurityConfigurerAdapter ,请检查注释:

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.authenticationProvider(new AuthenticationProvider() {

            @Override
            public Authentication authenticate(Authentication authentication) throws AuthenticationException {
                return null;  // this thing isn't called at all;
            }

            @Override
            public boolean supports(Class<?> aClass) {
                return false; // this thing isn't called at all;
            }
        });
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.addFilterAfter(new Filter() {

            @Override
            public void init(FilterConfig filterConfig) throws ServletException {

            }

            @Override
            public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
                HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
                String session = httpServletRequest.getHeader("session_id");
                // how do I tell spring that we're authorized here?
                filterChain.doFilter(servletRequest, servletResponse); 
            }

            @Override
            public void destroy() {

            }
        }, BasicAuthenticationFilter.class)
                .authorizeRequests()
                .antMatchers("/login").permitAll()
                .anyRequest().authenticated();
    }

}

我已经检查了很多主题,但是找不到完整的示例。

0 个答案:

没有答案