springboot整合security步骤

xiaoxiao2021-02-28  43

首先你需要自定义一个类,当然需要继承extends WebSecurityConfigurerAdapter类用@Configuration(声明这个类是配置文件)和@EnableWebSecurity(开启security安全声明)和@EnableGlobalMethodSecurity(prePostEnabled = true)(可以直接在controller的方法上声明注解,可以进行角色拦截)

然后重写configure(HttpSecurity http)的方法,这里面来自定义自己的拦截方法和业务逻辑。 security的大致过程是这样的。首先过滤器filter先拦截,然后调用mannger中的Provider来处理,设置统一信息返回处理让EntryPoint来处理返回请求。这里的类都需要自定义。并且在configure方法上声明才可以使用。

注意:只有filter类方法getPreAuthenticatedPrincipal不返回null才会走到provide中,如果不为null,则走到provide类的supports方法中,返回的布尔类型,如果为true,则走authenticate这个方法。为false则不走,出错的话走EntryPoint类,否则走controller里面对应的api 需要继承AbstractPreAuthenticatedProcessingFilter类和实现两个方法

public class RestPreAuthenticatedProcessingFilter extends AbstractPreAuthenticatedProcessingFilter{ @Override protected Object getPreAuthenticatedPrincipal(HttpServletRequest request) { return null; } @Override protected Object getPreAuthenticatedCredentials(HttpServletRequest httpServletRequest) { return null; } }

自定义provide 需要继承AuthenticationProvider和实现两个方法

public class RestAuthenticationProvider implements AuthenticationProvider{ @Override public Authentication authenticate(Authentication authentication){ } @Override public boolean supports(Class<?> authentication) { } }

设置统一信息返回处理类 需要继承AuthenticationEntryPoint,重写一个方法

public class RestAuthenticationEntryPoint implements AuthenticationEntryPoint{ @Override public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e){ } }

自定义过后还需要在configure方法中声明。有几个需要注意的地方 声明过滤器,因为过滤器需要一个Manager,所以要指定一个Manager。 并且Manager也需要指定里面的provide,因为是provide来处理逻辑的 所以config方法应该这样写

/** * 为验证拦截器设置AuthenticationManager (由于用了springboot注入方式) * @return * @throws Exception */ private RestPreAuthenticatedProcessingFilter getPreAuthenticatedProcessingFilter() throws Exception { RestPreAuthenticatedProcessingFilter filter = new RestPreAuthenticatedProcessingFilter(parameters.getNoneSecurityPath(),commonCacheUtil); filter.setAuthenticationManager(this.authenticationManagerBean()); return filter; } //指定provider @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.authenticationProvider(new RestAuthenticationProvider()); } @Override protected void configure(HttpSecurity http) throws Exception { http.csrf().disable() .authorizeRequests() .antMatchers(parameters.getNoneSecurityPath().toArray(new String[parameters.getNoneSecurityPath().size()])).permitAll()//符合条件的路径放过验证 // .anyRequest().hasRole("BIKE_CLIENT")//其他全部需要 BIKE_CLIENT 角色 .anyRequest().authenticated()//其他全部需要授权 .and().httpBasic().authenticationEntryPoint(new RestAuthenticationEntryPoint())//设置统一信息返回处理 .and() .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)//无状态请求 不需要session .and() .addFilter(getPreAuthenticatedProcessingFilter())//添加自定义登录验证过滤器 ; }
转载请注明原文地址: https://www.6miu.com/read-2614165.html

最新回复(0)