<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
<version>1.5.1.RELEASE</version>
</dependency>
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Bean
public UserDetailsService userDetailsService() {
return new CustomUserDetailsService();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().withUser("rhwayfun").password("1209").roles("USERS")
.and().withUser("admin").password("123456").roles("ADMIN");
//auth.jdbcAuthentication().dataSource(securityDataSource);
//auth.userDetailsService(userDetailsService());
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()//配置安全策略
//.antMatchers("/","/index").permitAll()//定义/请求不需要验证
.anyRequest().authenticated()//其余的所有请求都需要验证
.and()
.formLogin()
.loginPage("/login")
.defaultSuccessUrl("/index")
.permitAll()
.and()
.logout()
.logoutSuccessUrl("/login")
.permitAll();//定义logout不需要验证
http.csrf().disable();
}
}
@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter {
/**
* 统一注册纯RequestMapping跳转View的Controller
*/
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/login").setViewName("/login");
}
}
<!DOCTYPE html>
<%--<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>--%>
<html>
<head>
<meta charset="utf-8">
<title>Welcome SpringBoot</title>
<script src="/js/jquery-3.1.1.min.js"></script>
<script src="/js/index.js"></script>
</head>
<body>
<form name="f" action="/login" method="post">
<input id="name" name="username" type="text"/><br>
<input id="password" name="password" type="password"><br>
<input type="submit" value="login">
<input name="_csrf" type="hidden" value="${_csrf}"/>
</form>
<p id="users">
</p>
<script>
$(function () {
$('[name=f]').focus()
})
</script>
</body>
</html>
auth.inMemoryAuthentication()//基于内存进行认证
.withUser("rhwayfun").password("1209")//用户名密码
.roles("USERS")//USER角色
.and()
.withUser("admin").password("123456").roles("ADMIN");//ADMIN角色
auth.jdbcAuthentication().dataSource(securityDataSource);
public static final String DEF_CREATE_USER_SQL = "insert into users (username, password, enabled) values (?,?,?)"; public static final String DEF_INSERT_AUTHORITY_SQL = "insert into authorities (username, authority) values (?,?)"; public static final String DEF_USER_EXISTS_SQL = "select username from users where username = ?";
auth.userDetailsService(userDetailsService());
@Bean
public UserDetailsService userDetailsService() {
return new CustomUserDetailsService();
}
@Service
public class CustomUserDetailsService implements UserDetailsService {
/** Logger */
private static Logger log = LoggerFactory.getLogger(CustomUserDetailsService.class);
@Resource
private UserRepository userRepository;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
if (StringUtils.isBlank(username)) {
throw new IllegalArgumentException("username can't be null!");
}
User user;
try {
user = userRepository.findByUserName(username);
} catch (Exception e) {
log.error("读取用户信息异常,", e);
return null;
}
if (user == null) {
return null;
}
List<UserAuthority> roles = userRepository.findRoles(user.getUserId());
List<SimpleGrantedAuthority> authorities = new ArrayList<>();
for (UserAuthority role : roles) {
SimpleGrantedAuthority authority = new SimpleGrantedAuthority(String.valueOf(role.getAuthId()));
authorities.add(authority);
}
return new org.springframework.security.core.userdetails.User(username, "1234", authorities);
}
}
@Configuration
@ConfigurationProperties(prefix = "security.datasource")
@MapperScan(basePackages = DataSourceConstants.MAPPER_SECURITY_PACKAGE, sqlSessionFactoryRef = "securitySqlSessionFactory")
public class SecurityDataSourceConfig {
private String url;
private String username;
private String password;
private String driverClassName;
@Bean(name = "securityDataSource")
public DataSource securityDataSource() {
DruidDataSource dataSource = new DruidDataSource();
dataSource.setDriverClassName(driverClassName);
dataSource.setUrl(url);
dataSource.setUsername(username);
dataSource.setPassword(password);
return dataSource;
}
@Bean(name = "securityTransactionManager")
public DataSourceTransactionManager securityTransactionManager() {
return new DataSourceTransactionManager(securityDataSource());
}
@Bean(name = "securitySqlSessionFactory")
public SqlSessionFactory securitySqlSessionFactory(@Qualifier("securityDataSource") DataSource securityDataSource)
throws Exception {
final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
sessionFactory.setDataSource(securityDataSource);
sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver()
.getResources(DataSourceConstants.MAPPER_SECURITY_LOCATION));
return sessionFactory.getObject();
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getDriverClassName() {
return driverClassName;
}
public void setDriverClassName(String driverClassName) {
this.driverClassName = driverClassName;
}
}
public interface UserRepository{
User findByUserName(String username);
List<UserAuthority> findRoles(int userId);
}
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-3 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2026 源码网商城 (www.yuanmawang.com) 版权所有