项目中用到了权限,控制每个访问路径,实施具体权限,以防没有权限登陆后直接可以输入网址访问
数据库:role(权限表)
注:这个有个坑就是关于“ROLE_”这个的Spring security默认好像是自己添加了“ROLE_”Z,这个前缀的,后面会遇到
Spring security核心类
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* @time: 2018/12/24 11:02
* @description:
*/
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true, jsr250Enabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Resource
private UserDao userDao;
@Resource
private RoleDao roleDao;
@Autowired
private AuthenticationSuccessHandler authenticationSuccessHandler;
@Autowired
private AuthenticationFailureHandler authenticationFailureHandler;
/**
* @description:注册UserDetailsService的bean
* 以role角色作为角色判断,
**/
@Bean
UserDetailsService customUserService() {
return username -> {
Map temp = userDao.get(username);
if (null != temp) {
Integer userId = Integer.parseInt(String.valueOf(temp.get("userId")));
String userPassword = String.valueOf(temp.get("userPassword"));
List<Map<String, Object>> roles = roleDao.findByUserId(userId);
List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
if (null != roles) {
roles.forEach(role -> {
if (null != role) {
String roleName = String.valueOf(role.get("roleName"));
if (null != roleName) {
SimpleGrantedAuthority grantedAuthority = new SimpleGrantedAuthority(roleName);
grantedAuthorities.add(grantedAuthority);
}
}
});
}
return new org.springframework.security.core.userdetails.User(username, userPassword, grantedAuthorities);
} else {
throw new UsernameNotFoundException(username + " do not exist!");
}
};
}
/**
* @description: user details service 验证
**/
@Override
protected void configure(AuthenticationManagerBuilder auth) {
try {
auth.userDetailsService(customUserService())
// 验证密码MD5加密
.passwordEncoder(new PasswordEncoder() {
@Override
public String encode(CharSequence rawPassword) {
return Md5.getMd5(String.valueOf(rawPassword));
}
@Override
public boolean matches(CharSequence rawPassword, String encodedPassword) {
return encodedPassword.equals(Md5.getMd5(String.valueOf(rawPassword)));
}
});
} catch (Exception e) {
e.printStackTrace();
throw new IllegalParamException("用户名密码错误!");
}
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable();
http.authorizeRequests()
// 默认不拦截的url
.antMatchers("/").permitAll()
// 静态默认不拦截
.antMatchers("/image/**","/static/**","/templates/**").permitAll()
// 赋予权限 此处坑没有ROLE_
.antMatchers("/admin/**").hasAnyRole("ADMIN", "SYS")
.antMatchers("/sku/**", "/sort/**").hasAnyRole("USER", "ADMIN", "SYS")
.and()
.formLogin()
.loginPage("/login")
.defaultSuccessUrl("/index")
// 登陆失败的处理
.failureHandler(authenticationFailureHandler)
//.failureForwardUrl("/")
.permitAll()
.and()
.logout()
.permitAll();
}
}
配置网页进入跳转页面
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
* @time: 2018/12/24 12:20
* @description:
*/
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("test");
registry.addViewController("/index").setViewName("index");
}
}
登陆失败处理,这里是本来标准返回的就是json所以直接使用json返回格式
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jl.products.bean.Resp;
import com.jl.products.exception.UnauthorizedException;
import com.jl.products.util.ReturnCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.stereotype.Component;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* @time: 2018/12/25 9:19
* @description:
*/
@Component("authenticationFailureHandler")
public class AuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler {
@Autowired
private ObjectMapper objectMapper;
@Override
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
response.setContentType("application/json;charset=UTF-8");
System.out.println(new Resp<>(ReturnCode.USER_UNAUTHORIZED, exception.getMessage(), null));
response.getWriter().write(objectMapper.writeValueAsString(new Resp<>(ReturnCode.USER_UNAUTHORIZED, exception.getMessage(), null)));
//super.onAuthenticationFailure(request, response, exception);
}
}
登陆成功处理,本项目为用上
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* @time: 2018/12/25 9:12
* @description:
*/
@Component("authenticationSuccessHandler")
public class AuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {
@Autowired
private ObjectMapper objectMapper;
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws ServletException, IOException {
response.setContentType("application/json;charset=UTF-8");
response.getWriter().write(objectMapper.writeValueAsString(authentication));
//request.getSession().setAttribute("user", authentication.);
//super.onAuthenticationSuccess(request, response, authentication);
}
}
配置文件
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>