Security 退出登、权限控制
退出登陆
public class LogoutSecurityConfig implements WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.httpBasic()
.and()
.logout()
.logoutUrl("/logout")
.logoutSuccessUrl("/logout/page")
.deleteCookies("deleteCookie")
.and();
}
}
自定义退出成功处理器需要实现 LogoutSuccessHandler 接口
替换.logoutSuccessUrl("/logout/page")
@Autowired
private MyLogOutSuccessHandler logOutSuccessHandler;
@Component
public class MyLogOutSuccessHandler implements LogoutSuccessHandler {
@Override
public void onLogoutSuccess(HttpServletRequest request,
HttpServletResponse response,
Authentication authentication) throws IOException, ServletException {
response.setStatus(HttpStatus.UNAUTHORIZED.value());
response.setContentType("application/json;charset=utf-8");
response.getWriter().write("退出成功,请重新登录");
}
}
权限控制
开启注解
xml 开启
顺序
- @Secured
- @RolesAllowed
- SqEL : @PreAuthoreize 、 @PostAuthorize 、@PreFilter 、 @PostFilter
<global-method-security secured-annotations="enabled"/>
<global-method-security jsr250-annotations="enabled"/>
<global-method-security pre-post-annotations="enabled"/>
注解 开启方式
配置类中 @EnableGlobalMethodSecurity(prePostEnabled = true)
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {}
注解说明
@Secured
@Secured("role_admin","..")
public void T(){}
@RolesAllowed
和@Secyred 功能一样,只是缺少元注解@Inherited
SqEL
@PreAuthorize访问方法前对权限验证 @PreFilter 访问方法前对参数验证 @PostAuthorize 访问方法后验证权限 @PostFilter 方法返回参数验证
@PreAuthorize("hasRole()'role_user') and form.note.length()<= 100 or hasRole('role_vip')")
public void T(){}
@PreAuthorize("#user.name.equals('lf')")
public void T(User user){}
@PreAuthorize("hasAuthorize('admin')")
public void T(){}
和@PreFilter中 有一个filterObject 表示集合中方的对象。
@PostFilter("filterObject.id%2==0")
public List<User> seleteAll(){}
多个对象时 使用filterTarget 来指定
@PreFilter(filterTarget="ids",value="filterObjcet%2==0")
public void delete(List<User> ids,List<role> role){}
自定义权限不足处理器
实现AccessDeniedHandler 接口
@Component
public class MyAccessDeniedHandler implements AccessDeniedHandler {
@Override
public void handle(HttpServletRequest request,
HttpServletResponse response,
AccessDeniedException accessDeniedException) throws IOException, ServletException {
response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
response.setContentType("application/json;charset=utf-8");
response.getWriter().write("很抱歉,您没有该访问权限");
}
}
配置类设置
@Autowired
private MyAccessDeniedHandler accessDeniedHandler;
....
http.exceptionHandling()
.accessDeniedHandler(accessDeniedHandler);
底部
|