<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
@Configurable
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)//允许进入页面方法前检验
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private MyAuthenticationProvider provider;//自定义验证
@Autowired
private UserDetailsService userDetailsService;//自定义用户服务
@Autowired
public void configAuthentication(AuthenticationManagerBuilder auth) throws Exception{
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers(StaticParams.PATHREGX.NOAUTH,
StaticParams.PATHREGX.CSS,StaticParams.PATHREGX.JS,StaticParams.PATHREGX.IMG).permitAll()//无需访问权限
.antMatchers(StaticParams.PATHREGX.AUTHADMIN).hasAuthority(StaticParams.USERROLE.ROLE_ADMIN)//admin角色访问权限
.antMatchers(StaticParams.PATHREGX.AUTHUSER).hasAuthority(StaticParams.USERROLE.ROLE_USER)//user角色访问权限
.anyRequest()//all others request authentication
.authenticated()
.and()
.formLogin().loginPage("/login").permitAll()
.and()
.logout().permitAll();
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
//将验证过程交给自定义验证工具
auth.authenticationProvider(provider);
}
@ResponseBody
@PreAuthorize("hasAuthority('"+StaticParams.USERROLE.ROLE_ADMIN+"')")//这里可以指定特定角色的用户访问权限
@RequestMapping(value = "adminrequire", method = RequestMethod.GET)
public String adminrequire(){
return "HELLO from web but you should be admin";
}
/*用户表*/
@Entity
@Table(name = "user")
public class SystemUser {
@Id
@Column(name = "id")
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String userName;
private String password;
public SystemUser(){}
public SystemUser(SystemUser user){
this.userName = user.getUserName();
this.password = user.getPassword();
this.id = user.getId();
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
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;
}
}
/*角色表*/
@Entity
@Table(name = "user_role")
public class UserRole {
@Id
@Column(name = "id")
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String role;
private Long userId;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
public Long getUserId() {
return userId;
}
public void setUserId(Long userId) {
this.userId = userId;
}
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("user").password("password").roles("USER");
}
public class MyUserDetails extends SystemUser implements UserDetails{
private List<UserRole> roles;
public MyUserDetails(SystemUser user, List<UserRole> roles){
super(user);
this.roles = roles;
}
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
if(roles == null || roles.size() <1){
return AuthorityUtils.commaSeparatedStringToAuthorityList("");
}
StringBuilder commaBuilder = new StringBuilder();
for(UserRole role : roles){
commaBuilder.append(role.getRole()).append(",");
}
String authorities = commaBuilder.substring(0,commaBuilder.length()-1);
return AuthorityUtils.commaSeparatedStringToAuthorityList(authorities);
}
@Override
public String getPassword() {
return super.getPassword();
}
@Override
public String getUsername() {
return super.getUserName();
}
@Override
public boolean isAccountNonExpired() {
return true;
}
@Override
public boolean isAccountNonLocked() {
return true;
}
@Override
public boolean isCredentialsNonExpired() {
return true;
}
@Override
public boolean isEnabled() {
return true;
}
}
@Service("MyUserDetailsImpl")
public class MyUserDetailsService implements UserDetailsService {
@Resource(name = "SystemUserServiceImpl")
private SystemUserService systemUserService;
@Resource(name = "UserRoleServiceImpl")
private UserRoleService userRoleService;
@Override
public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
SystemUser user;
try {
user = systemUserService.findByName(userName);
} catch (Exception e) {
throw new UsernameNotFoundException("user select fail");
}
if(user == null){
throw new UsernameNotFoundException("no user found");
} else {
try {
List<UserRole> roles = userRoleService.getRoleByUser(user);
return new MyUserDetails(user, roles);
} catch (Exception e) {
throw new UsernameNotFoundException("user role select fail");
}
}
}
}
@Component
public class MyAuthenticationProvider implements AuthenticationProvider {
@Autowired
private MyUserDetailsService userService;
/**
* 自定义验证方式
*/
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
String username = authentication.getName();
String password = (String) authentication.getCredentials();
MyUserDetails user = (MyUserDetails) userService.loadUserByUsername(username);
if(user == null){
throw new BadCredentialsException("Username not found.");
}
//加密过程在这里体现
if (!password.equals(user.getPassword())) {
throw new BadCredentialsException("Wrong password.");
}
Collection<? extends GrantedAuthority> authorities = user.getAuthorities();
return new UsernamePasswordAuthenticationToken(user, password, authorities);
}
@Override
public boolean supports(Class<?> arg0) {
return true;
}
}
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有