Spring Security 参考手册
这是springsecurity的官方手册,如果需要详细了解可前往此处;
<dependencies>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
<version>4.2.10.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<version>4.2.10.RELEASE</version>
</dependency>
<!-- 标签库 -->
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-taglibs</artifactId>
<version>4.2.10.RELEASE</version>
</dependency>
</dependencies>
<!-- 权限过滤Filter -->
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
UserDetailsService userDetailsService;
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// TODO Auto-generated method stub
//super.configure(auth);
auth.userDetailsService(userDetailsService).passwordEncoder(new BCryptPasswordEncoder());
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/static/**","/login.jsp").permitAll()
.anyRequest().authenticated();//剩下都需要认证
// /login.jsp==POST 用户登陆请求发给Security
http.formLogin().loginPage("/toLogin")
.usernameParameter("loginacct").passwordParameter("userpswd")
.loginProcessingUrl("/login")
.defaultSuccessUrl("/main").permitAll();
http.csrf().disable();
http.logout().logoutSuccessUrl("/index");
//异常处理器
http.exceptionHandling().accessDeniedHandler(new AccessDeniedHandler() {
@Override
public void handle(HttpServletRequest request, HttpServletResponse response,
AccessDeniedException accessDeniedException) throws IOException, ServletException {
String type=request.getHeader("X-Requested-With");
if ("XMLHttpRequest".equals(type)) {
//ajax 通过流的形式
//response.getWriter().print("403");//403权限不够
}else {
request.getRequestDispatcher("/WEB-INF/jsp/error/error403.jsp").forward(request, response);
}
}
});
http.rememberMe();
}
}
@Component
public class SecurityUserDetailServiceImpl implements UserDetailsService {
@Autowired
TAdminMapper adminMapper;
@Autowired
TRoleMapper roleMapper;
@Autowired
TPermissionMapper permissionMapper;
Logger log=LoggerFactory.getLogger(SecurityUserDetailServiceImpl.class);
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
// TODO Auto-generated method stub
/*
* SELECT t_role.* FROM t_role JOIN t_admin_role ON t_role.id = t_admin_role.roleid WHERE t_admin_role.adminid=2
*
*
* */
// 1查询用户对象
TAdminExample example = new TAdminExample();
example.createCriteria().andLoginacctEqualTo(username);
List<TAdmin> list = adminMapper.selectByExample(example);
log.debug("用户信息{}",list);
if (list != null && list.size() == 1) {
TAdmin admin = list.get(0);
Integer adminId = admin.getId();
log.debug("用户信息{}",admin);
// 1查询角色集合
List<TRole> roleList = roleMapper.listRoleByAdminId(adminId);
log.debug("用户角色{}",roleList);
// 查询权限集合
List<TPermission> permissionList = permissionMapper.listPermissionByAdminId(adminId);
// 构建用户所有权限集合==》(ROLE_角色+权限)
Set<GrantedAuthority> authorities=new HashSet<GrantedAuthority>();
for (TRole role : roleList) {
authorities.add(new SimpleGrantedAuthority("ROLE_"+role.getName()));
}
for (TPermission permission : permissionList) {
authorities.add(new SimpleGrantedAuthority("ROLE_"+permission.getName()));
}
log.debug("用户总权限集合{}",authorities);
// 第一个参数分别是 账号 密码 权限集合
//return new User(admin.getLoginacct(), admin.getUserpswd(), authorities);
return new TSecurityAdmin(admin, authorities);
}else {
return null;
}
}
}
public class TSecurityAdmin extends User {
TAdmin admin;
public TSecurityAdmin(TAdmin admin,Set<GrantedAuthority> authorities) {
super(admin.getLoginacct(), admin.getUserpswd(), true, true, true, true, authorities);
this.admin=admin;
}
}
<!-- 核心控制器 -->
<!-- The front controller of this Spring Web application, responsible for
handling all application requests -->
<servlet>
<servlet-name>springDispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath*:/spring/springmvc.xml
classpath*:/spring/spring-*.xml
</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<!-- Map all requests to the DispatcherServlet for handling -->
<servlet-mapping>
<servlet-name>springDispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!-- 创建Spring IOC容器 -->
<!-- needed for ContextLoaderListener -->
<!-- <context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:/spring/spring-*.xml</param-value>
</context-param>
Bootstraps the root web application context before servlet initialization
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener> -->
@PreAuthorize("hasRole('项目经理')")
@RequestMapping("admin/doAdd")
public String doAdd(TAdmin admin) {
adminService.saveTAdmin(admin);
return "redirect:/admin/index?pageNum="+Integer.MAX_VALUE;
<sec:authorize access="hasRole('组长')">
<button type="button" class="btn btn-default btn-danger">
<span class="glyphicon glyphicon-question-sign"></span> 帮助
</button>
</sec:authorize>