Security
POM加入springsecurity依赖,任何接口都被保护起来了,用户及密码是每次访问随机生成的
手工配置用户名及口令,可以在数据库里面配置或在配置文件里面配置
第一种:配置文件
spring.security.user.password=123
spring.security.user.name=gcmax
spring.security.user.roles=admin
第二种:securityconfg extends websecurityConfigurerAdapter
configure
内存里面配置
密码加密
BCryptPasswordEncoder encoder=new BCryptPasswordEncoder();
encoder.encode("123");
PasswordEncoder passwordEncoder(){
return NoOpPasswordEncoder.getInstance();, 这里改成return new BCryptPasswordEncoder();
}
方法安全
方法上面加上注解
@PreAuthorize("hasRole('admin')")
public String admin(){
return "hello admin";
}
@Secured("ROLB_user")
public String user(){
return "hello user";
}
基于数据库安全认证
security-josn
@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
if (!request.getMethod().equals("POST")) {
throw new AuthenticationServiceException(
"Authentication method not supported: " + request.getMethod());
}
if (request.getContentType().equals(MediaType.APPLICATION_JSON_VALUE)) {
//说明用户以 JSON 的形式传递的参数
String username = null;
String password = null;
try {
Map<String, String> map = new ObjectMapper().readValue(request.getInputStream(), Map.class);
username = map.get("username");
password = map.get("password");
} catch (IOException e) {
e.printStackTrace();
}
if (username == null) {
username = "";
}
if (password == null) {
password = "";
}
username = username.trim();
UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(
username, password);
// Allow subclasses to set the "details" property
setDetails(request, authRequest);
return this.getAuthenticationManager().authenticate(authRequest);
}
return super.attemptAuthentication(request, response);
}
}