Spring boot Security 登陆安全配置

实现的效果

  访问url时,如果未登录时跳转到Login界面,要求用户登陆,如果登陆过返回请求的数据。

效果图

访问数据时,未登录返回login界面 

 

 

 

登陆操作

登陆成功进入登出界面

 

 

登陆成功后再次访问数据

 

 

 

 

POM 文件

加入 Security 配置,数据库使用maybatis。 

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.6.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <groupId>com.gailguo</groupId>
    <artifactId>login</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>login</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.0.1</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>

    </dependencies>


    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

  

 

 

WebSecurityConfigurerAdapter配置Security信息

1.  authorizeRequests() .antMatchers("/user/*").permitAll()  .anyRequest().authenticated() 意思代表 /user 不需要进行授权认证,其他都需要认证。
2 .formLogin().loginPage("/login.html").loginProcessingUrl("/signin").successHandler(successHandler).failureHandler(failureHandler) 设置的登陆界面,和登陆的url 以及登陆成功的handler和失败的handler。
3 .usernameParameter("username").passwordParameter("password").permitAll()  用户名和密码的传参数 

4 .logout().logoutUrl("/signout").logoutSuccessHandler(logoutSuccessHandler).permitAll(); 登出url ,以及handler

5
.csrf().disable()


@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private AjaxAuthSuccessHandler successHandler;

    @Autowired
    private AjaxAuthFailureHandler failureHandler;

    @Autowired
    private AjaxLogoutSuccessHandler logoutSuccessHandler;

    @Autowired
    private UserDetailsServiceImpl userDetailsService;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests().antMatchers("/user/*").permitAll() .anyRequest().authenticated()
                .and()
                .csrf().disable()
                .formLogin().loginPage("/login.html").loginProcessingUrl("/signin").successHandler(successHandler).failureHandler(failureHandler)
                .usernameParameter("username").passwordParameter("password").permitAll()
                .and()
                .logout().logoutUrl("/signout").logoutSuccessHandler(logoutSuccessHandler).permitAll();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(new PasswordEncoder() {
            @Override
            public String encode(CharSequence charSequence) {
                return charSequence.toString();
            }

            @Override
            public boolean matches(CharSequence charSequence, String s) {
                return s.equals(charSequence.toString());
            }
        });
    }
}

  

 

SimpleUrlAuthenticationSuccessHandler 

 登陆成功时

@Component
public class AjaxAuthSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {

    private static final Logger logger = LoggerFactory.getLogger(AjaxAuthSuccessHandler.class);

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        logger.info("Authentication success, {} login successfully", request.getParameter("username"));
        response.setStatus(HttpServletResponse.SC_OK);
        response.sendRedirect("/home.html");
    }
}

 

 

fail

@Component
public class AjaxAuthFailureHandler extends SimpleUrlAuthenticationFailureHandler {

    private static final Logger logger = LoggerFactory.getLogger(AjaxAuthFailureHandler.class);

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        logger.info("Authentication error, {} login failed", request.getParameter("username"));
        response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Authentiaction Failed");
    }
}

  

 

loginout success

@Component
public class AjaxLogoutSuccessHandler implements LogoutSuccessHandler {

    private static final Logger logger = LoggerFactory.getLogger(AjaxLogoutSuccessHandler.class);

    @Override
    public void onLogoutSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
        httpServletResponse.setStatus(HttpServletResponse.SC_OK);
        logger.info("Logout successfully, session id: {}", httpServletRequest.getSession().getId());
    }
}

 

 

UserDetailsService

@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    private Map<String, String> userRepository = new HashMap<>();

    @PostConstruct
    private void init() {
        userRepository.put("zhangshan", "123456");
        userRepository.put("guo", "123456");
    }

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        return new User(s, userRepository.get(s), new ArrayList<>());
    }
}

  

 代码:

https://github.com/galibujianbusana/login

  

 

posted @ 2019-08-11 22:00  咖喱不见不散啊  阅读(813)  评论(0编辑  收藏  举报