spring實戰-Spring-security實現使用者許可權認證登入
阿新 • • 發佈:2018-11-04
第八篇:Spring-security實現使用者許可權認證登入
spring-security原本是Acegi Security元件,該元件是一個強大的安全框架,但是使用方式很繁瑣,要配置幾百行XML。整合進Spring後,就可以通過xml或者JavaConfig的方式,很容易的就實現了系統的整合。下面示例展示了通過JavaConfig的方式整合spring-security安全框架
1,實現AbstractSecurityWebApplicationInitializer,只用寫好一個實現類就可以了,Spring系統會發現他,並用他在web容器中註冊DelegetingFilterProxy。DelegetingFilterProxy會攔截髮往應用中的請求。並將請求委託給一個ID為springSecurityFilterChain的bean,該bean可以連線一個或任意多個Filter,Spring security就是依賴著一系列servlet filter來提供不同的安全特性。這些細節我們不用管,當啟用web安全性時,會自動建立這些filter。
package com.halfworlders.idat.security;
import org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer;
public class SecurityWebInitializer extends AbstractSecurityWebApplicationInitializer {
}
2,建立SecurityConfig
3,在TilesWebConfig中匯入配置package com.halfworlders.idat.config; import javax.sql.DataSource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.crypto.password.StandardPasswordEncoder; import com.halfworlders.idat.security.IdatUserDetailsService; import com.halfworlders.idat.service.Userservice; @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { // @Autowired // private DataSource dataSource; @Autowired private Userservice userservice; @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { /* * 可以通過記憶體設定的方式,來做使用者登入驗證,此種方式比較適合開發和測試階段使用 */ /*auth .inMemoryAuthentication() .withUser("admin") .password("admin") .roles("ADMIN");*/ /* * 可以通過資料來源設定的方式,直接基於資料庫的驗證,還可以設定密碼加密, * 但此種方式要求資料庫的使用者表結構必須符合spring-security的要求 * 一下配上sql */ /*auth .jdbcAuthentication() .dataSource(dataSource) .passwordEncoder(new StandardPasswordEncoder("idatpwd"));*/ /* * 最好的是基於UserDetailService的介面方式,這樣spring-security並不知道系統通過什麼樣的方式來實現使用者資料驗證 * 開發人員可以在介面內以任意方式實現,增加了系統的靈活性 */ auth.userDetailsService(new IdatUserDetailsService(userservice)); } }
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "com.halfworlders.idat.controller")
@Import(SecurityConfig.class)
public class TilesWebConfig extends WebMvcConfigurerAdapter {
。。。。。
}
只需這三步,就能輕鬆的啟用了Spring security安全框架
另外再需要實現UserDetailsService
package com.halfworlders.idat.security; import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import com.halfworlders.idat.service.Userservice; public class IdatUserDetailsService implements UserDetailsService{ private final Userservice userservice; public IdatUserDetailsService(Userservice userservice) { this.userservice = userservice; } @Override public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException { User user = userservice.findUserByName(userName); if (null != user) { return user; } throw new UsernameNotFoundException("User name" + userName + "not find"); } }
UserService
package com.halfworlders.idat.service;
import org.springframework.security.core.userdetails.User;
public interface Userservice {
User findUserByName(String userName);
}
package com.halfworlders.idat.service.impl;
import java.util.ArrayList;
import java.util.List;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Service;
import com.halfworlders.idat.service.Userservice;
@Service
public class UserServiceImpl implements Userservice {
@Override
public User findUserByName(String userName) {
List<GrantedAuthority> grantedAuthorities = new ArrayList<GrantedAuthority>();
grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
return new User(userName, "admin", grantedAuthorities);
}
}
mysql-sql
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for authorities
-- ----------------------------
DROP TABLE IF EXISTS `authorities`;
CREATE TABLE `authorities` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(20) DEFAULT NULL,
`authority` varchar(50) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Table structure for groups
-- ----------------------------
DROP TABLE IF EXISTS `groups`;
CREATE TABLE `groups` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`groupName` varchar(50) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Table structure for group_authorities
-- ----------------------------
DROP TABLE IF EXISTS `group_authorities`;
CREATE TABLE `group_authorities` (
`group_Id` int(11) NOT NULL AUTO_INCREMENT,
`authority` varchar(50) DEFAULT NULL,
PRIMARY KEY (`group_Id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Table structure for group_members
-- ----------------------------
DROP TABLE IF EXISTS `group_members`;
CREATE TABLE `group_members` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`userName` varchar(20) DEFAULT NULL,
`group_Id` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Table structure for users
-- ----------------------------
DROP TABLE IF EXISTS `users`;
CREATE TABLE `users` (
`id` int(8) NOT NULL AUTO_INCREMENT,
`userName` varchar(20) DEFAULT NULL,
`password` varchar(50) DEFAULT NULL,
`enabled` tinyint(4) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;