继续使用上篇文章SpringSecurity第一章所建的工程
1.核心配置如下
eureka注册中心我就不说了,我博客里面有eureka文章,供参考eureka注册中心实例
server:
port: 8787
spring:
application:
name: xwl-git-server
jpa:
hibernate:
ddl-auto: update
datasource:
password: 123456
username: root
url: jdbc:mysql://localhost:3306/mtqiushui.dispatching?characterEncoding=utf-8
driver-class-name: com.mysql.jdbc.Driver
#视图 静态资源位置解析
#static-path-pattern: /**
resources:
static-locations: classpath:/templates/,classpath:/resources/,classpath:/static/,classpath:/public/
eureka:
instance:
hostname: localhost
client:
service-url:
defaultZone: http://localhost:8764/eureka/
logging:
level:
root: INFO
org.hibernate: INFO
org.hibernate.type.descriptor.sql.BasicBinder: TRACE
org.hibernate.type.descriptor.sql.BasicExtractor: TRACE
com.springms: DEBUG
2.自定义用户认证逻辑
package com.itxwl.xwlgetserver.config;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
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 org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;
/**
* 自定义用户逻辑
*/
@Component
public class MyUserDetailsService implements UserDetailsService {
private Logger logger= LoggerFactory.getLogger(getClass());
//SpringSecurity提供密码加密接口
@Autowired
private PasswordEncoder passwordEncoder;
@Override
public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
logger.info("登陆用户名"+s);
//第三个参数代表用户的权限 授权 告诉我返回的用户拥有哪些权限
//根据查找到的用户名判断用户是否被冻结
return new User(s,
//对密码进行加密
passwordEncoder.encode("1234566"),
true,true,true,true,
AuthorityUtils.commaSeparatedStringToAuthorityList("admin"));
}
}
3.登陆认证成功返回类处理
package com.itxwl.xwlgetserver.config;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Component
public class isSuccessHandler implements AuthenticationSuccessHandler {
private Logger logger = LoggerFactory.getLogger(getClass());
@Autowired
private ObjectMapper objectMapper;
@Override
public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
logger.info("登陆成功");
httpServletResponse.setContentType("application/json;charset=UTF-8");
httpServletResponse.getWriter().write(objectMapper.writeValueAsString(authentication));
}
}
4.登陆认证失败处理类
package com.itxwl.xwlgetserver.config;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.http.HttpStatus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Component
public class errorHandler implements AuthenticationFailureHandler {
private Logger logger = LoggerFactory.getLogger(getClass());
@Autowired
private ObjectMapper objectMapper;
@Override
public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
logger.info("登陆失败");
httpServletResponse.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR);
httpServletResponse.setContentType("application/json;charset=UTF-8");
httpServletResponse.getWriter().write(objectMapper.writeValueAsString(e));
}
}
5.SpringSecurity认证配置类
package com.itxwl.xwlgetserver.config;
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.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
/**
* 表示这是一个配置
*/
@Configuration
public class BrowerSecurityConfig extends WebSecurityConfigurerAdapter {
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
//注册认证成功处理类
@Autowired
private isSuccessHandler successHandler;
//注册认证失败处理类
@Autowired
private errorHandler errorhandler;
@Override
protected void configure(HttpSecurity http) throws Exception {
//默认跳转成功之后的页面为defaultSuccessUrl("/success.html",true)
http.formLogin()
//指定登陆自定义页面
.loginPage("/authentication/require")
//需要告知表单提交时 的url
.loginProcessingUrl("/authentication/form")
//登陆认证成功处理
.successHandler(successHandler)
//登陆认证失败处理
.failureHandler(errorhandler)
.and()
//所有request请求进行授权
.authorizeRequests()
//当访问这个url时不需要身份认证
.antMatchers("/authentication/require","/login.html","/success.html").permitAll()
//任何请求
.anyRequest()
//都需要身份认证
.authenticated();
//将默认的防护tocken功能关闭
http.csrf().disable();
}
}
6.实例结构图(以及idea设置静态页面存储操作)
7.流程图