接着上一篇( springboot 集成mybatis)繼續搞,接下來集成security
首先還是添加pom依賴
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
建表(如果TB_USER已經建了,則不需要再建)
CREATE TABLE `TB_USER` (
`ID` varchar(32) NOT NULL ,
`USER_NAME` varchar(32) NOT NULL ,
`PASSWORD` varchar(32) NOT NULL ,
`ENABLE` varchar(2) NOT NULL DEFAULT '1' ,
`PHONE` varchar(11) NULL ,
`EMAIL` varchar(32) NULL ,
`EXTEND_FIELD` text NULL ,
`CREATE_TIME` datetime NOT NULL DEFAULT now() ,
`UPDATE_TIME` datetime NOT NULL DEFAULT now() ,
PRIMARY KEY (`ID`)
);
CREATE TABLE `TB_RESOURCE` (
`ID` varchar(32) NOT NULL,
`FATHER_ID` varchar(32) NOT NULL,
`CODE` varchar(32) NOT NULL,
`TITLE` varchar(32) DEFAULT NULL,
`URL` varchar(32) DEFAULT NULL,
`ICON` varchar(32) DEFAULT NULL,
`STATUS` varchar(2) DEFAULT NULL,
`LEVEL` int(11) DEFAULT NULL,
`CREATE_TIME` datetime DEFAULT now(),
`UPDATE_TIME` datetime DEFAULT now(),
PRIMARY KEY (`ID`)
);
CREATE TABLE `TB_ROLE` (
`ID` varchar(32) NOT NULL,
`NAME` varchar(32) NOT NULL,
`DESCRIPTION` varchar(32) NOT NULL,
`STATUS` varchar(2) DEFAULT NULL,
`CREATE_TIME` datetime DEFAULT now(),
`UPDATE_TIME` datetime DEFAULT now(),
PRIMARY KEY (`ID`)
);
CREATE TABLE `TB_ROLE_RESOURCE` (
`ID` varchar(32) NOT NULL,
`ROLE_ID` varchar(32) NOT NULL,
`RESOURCE_ID` varchar(32) NOT NULL,
`STATUS` varchar(2) DEFAULT NULL,
`CREATE_TIME` datetime DEFAULT now(),
`UPDATE_TIME` datetime DEFAULT now(),
PRIMARY KEY (`ID`)
);
CREATE TABLE `TB_USER_ROLE` (
`ID` varchar(32) NOT NULL,
`ROLE_ID` varchar(32) NOT NULL,
`USER_ID` varchar(32) NOT NULL,
`STATUS` varchar(2) DEFAULT NULL,
`CREATE_TIME` datetime DEFAULT now(),
`UPDATE_TIME` datetime DEFAULT now(),
PRIMARY KEY (`ID`)
);
接下來是java安全驗證相關的一些代碼編輯
1.自定義SabUserDetailsService實現UserDetailsService接口,重寫loadUserByUsername方法,可以從數據庫讀取
/**
* override query user by user name
*/
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
if (StringUtils.isEmpty(username)) {
logger.error("username is empty");
throw new UsernameNotFoundException("username is empty");
}
// query from cache
// UserDetails user = userCache.get(username);
springboot.demo.dmo.User user = userMapper.findByUserName(username);
if (null == user) {
logger.warn("get user is null, userName:{}", username);
// return empty user
return new User(username, "", new HashSet<GrantedAuthority>());
}
Set<GrantedAuthority> authorities = new HashSet<GrantedAuthority>();
if (!CollectionUtils.isEmpty(user.getRoleList())) {
for (Role role : user.getRoleList()) {
GrantedAuthority auth = new SimpleGrantedAuthority(role.getName());
authorities.add(auth);
}
}
// return user bean
return new User(user.getUserName(), user.getPassword(), authorities);
}
2.自定義SabSourceService實現FilterInvocationSecurityMetadataSource接口,啓動是加載db數據到內存
@Component
public class SabSourceService implements FilterInvocationSecurityMetadataSource {
@Autowired
private ResourceMapper resourceMapper;
private static Map<String, Collection<ConfigAttribute>> resourceMap = new ConcurrentHashMap<String, Collection<ConfigAttribute>>();
/*
* 一定要加上@PostConstruct註解 在Web服務器啓動時,提取系統中的所有權限。
*/
@PostConstruct
private void loadResourceDefine() {
this.loadResource();
}
public void loadResource(){
/*
* 應當是資源爲key, 權限爲value。 資源通常爲url, 權限就是那些以ROLE_爲前綴的角色。 一個資源可以由多個權限來訪問。
*/
List<Resource> resList = resourceMapper.loadAll();
if (!CollectionUtils.isEmpty(resList)) {
for (Resource resource : resList) {
List<ConfigAttribute> attList = new ArrayList<ConfigAttribute>();
if (!CollectionUtils.isEmpty(resource.getRoleList())) {
for (Role role : resource.getRoleList()) {
ConfigAttribute ca = new SecurityConfig(role.getName());
attList.add(ca);
}
}
resourceMap.put(resource.getUrl(), attList);
}
}
}
@Override
public Collection<ConfigAttribute> getAllConfigAttributes() {
return new ArrayList<ConfigAttribute>();
}
@Override
public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {
FilterInvocation filterInvocation = (FilterInvocation) object;
if (resourceMap == null) {
loadResourceDefine();
}
Iterator<String> ite = resourceMap.keySet().iterator();
while (ite.hasNext()) {
String resURL = ite.next();
RequestMatcher requestMatcher = new AntPathRequestMatcher(resURL);
if (requestMatcher.matches(filterInvocation.getHttpRequest())) {
return resourceMap.get(resURL);
}
}
return null;
}
@Override
public boolean supports(Class<?> clazz) {
return true;
}
}
3.自定義SabAccessDecisionManager實現AccessDecisionManager接口,重寫decide方法,自定義權限規則
public void decide(Authentication authentication, Object object, Collection<ConfigAttribute> configAttributes)
throws AccessDeniedException, InsufficientAuthenticationException {
if (configAttributes == null) {
return;
}
Iterator<ConfigAttribute> ite = configAttributes.iterator();
while (ite.hasNext()) {
ConfigAttribute ca = ite.next();
String needRole = ((SecurityConfig) ca).getAttribute();
for (GrantedAuthority ga : authentication.getAuthorities()) {
if (needRole.trim().equals(ga.getAuthority().trim())) {
return;
}
}
}
throw new AccessDeniedException("權限不足");
}
4.自定義攔截器SabSecurityInterceptor集成FilterSecurityInterceptor
@Component
public class SabSecurityInterceptor extends FilterSecurityInterceptor{
@Resource(name = "sabSourceService")
private SabSourceService sourceService;
@Resource(name = "authenticationManager")
private AuthenticationManager authenticationManager;
@Resource(name = "sabAccessDecisionManager")
private SabAccessDecisionManager accessDecisionManager;
@PostConstruct
public void init() {
super.setAuthenticationManager(authenticationManager);
super.setAccessDecisionManager(accessDecisionManager);
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
FilterInvocation fi = new FilterInvocation(request, response, chain);
if (SecurityContextHolder.getContext().getAuthentication() == null || null == fi || fi.getRequestUrl().contains(".js")
|| fi.getRequestUrl().contains(".css")) {
chain.doFilter(request, response);
} else {
invoke(fi);
}
}
public void invoke(FilterInvocation fi) throws IOException, ServletException {
InterceptorStatusToken token = super.beforeInvocation(fi);
try {
fi.getChain().doFilter(fi.getRequest(), fi.getResponse());
} finally {
super.afterInvocation(token, null);
}
}
@Override
public Class<?> getSecureObjectClass() {
return FilterInvocation.class;
}
@Override
public SecurityMetadataSource obtainSecurityMetadataSource() {
return sourceService;
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {
// TODO Auto-generated method stub
}
@Override
public void destroy() {
// TODO Auto-generated method stub
}
}
5.自定義SecurityConfig繼承WebSecurityConfigurerAdapter,重寫configure方法,這裏面的權限校驗的規則配置
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Resource(name = "sabUserDetailsService")
UserDetailsService userDetailsService;
@Resource(name = "sabSecurityInterceptor")
FilterSecurityInterceptor securityInterceptor;
@Autowired
public void configAuthentication(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService);
}
/**
* base config
*/
@Override
protected void configure(HttpSecurity http) throws Exception {
http.headers().frameOptions().disable();
http.addFilterBefore(securityInterceptor, FilterSecurityInterceptor.class)// 在正確的位置添加我們自定義的過濾器
.authorizeRequests()
.antMatchers("/reloadResource").permitAll() // 刷新資源權限
.antMatchers("/**.*").authenticated()// .後綴認證
.and().formLogin().loginPage("/login").loginProcessingUrl("/login").usernameParameter("username")
.passwordParameter("password").defaultSuccessUrl("/loginSuccess").failureUrl("/loginFail").and()
.logout().logoutSuccessUrl("/login").logoutUrl("/logout")// login
.and().exceptionHandling().accessDeniedPage("/403")//
.and().csrf().disable() // disable csrf
.rememberMe().tokenRepository(new InMemoryTokenRepositoryImpl()).tokenValiditySeconds(86400);// remember
// me
}
/**
* fliter ignoring ,such as static
*/
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/resources/**");
}
}
@RequestMapping("login")
public ModelAndView login() {
return new ModelAndView("login");
}
@RequestMapping("logout")
public String logout(HttpServletRequest request) {
try {
request.logout();
} catch (ServletException e) {
e.printStackTrace();
}
return "redirect:/login";
}
至此已經基本完成,訪問應用,發現跳轉login頁面,輸入維護在庫裏面的用戶名、密碼即可登錄,ddl,dml可以參考下面源碼
git clone https://github.com/cm-jornada/demo.git
git checkout security