跟我学Spring Security配置(使用Java配置和注解)

@Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private UserDetailServiceImpl userDetailService; //对每个请求进行细粒度安全性控制的关键在于重载一下方法 @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests()//该方法所返回的对象的方法来配置请求级别的安全细节 .antMatchers("/login") .permitAll()//对于登录路径不进行拦截 .antMatchers("/show").authenticated()//authenticated()表示允许过的用户访问 .and() .formLogin()//配置登录页面 .loginPage("/login")//登录页面的访问路径 .loginProcessingUrl("/check")//登录页面下表单提交的路径 .failureUrl("/login")//登录失败后跳转的路径 .defaultSuccessUrl("/show")//登录成功后默认跳转的路径 .and() .csrf()//启用防跨站伪请求攻击,默认启用 .and() .logout()//用户退出操作 .logoutUrl("/logout")//用户退出所访问的路径,需要使用Post方式 .permitAll() .logoutSuccessUrl("/login?logout=true") .and() .authorizeRequests() // //定义路径保护的配置方法 // .antMatchers(HttpMethod.GET,"/admin") // .authenticated() .antMatchers(HttpMethod.GET,"/message/**","/object/**").hasRole("USER") .anyRequest().permitAll() .and() .rememberMe()//启用记住我功能 .tokenValiditySeconds(2419200) ; } //配置Spring Security的Filter链 @Override public void configure(WebSecurity web) throws Exception { super.configure(web); } //配置user-detail服务 @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(userDetailService) .passwordEncoder(new StandardPasswordEncoder("53cr3t"))//密码加密方式 ; // auth.inMemoryAuthentication() //内置用户 // .withUser("user").password("user").roles("USER"); } } 

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/ba17f711a0d96bcfbd9f5f89606dfaca.html