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

  

 

原文地址:https://www.cnblogs.com/galibujianbusana/p/11336940.html

时间: 2024-08-01 20:46:10

Spring boot Security 登陆安全配置的相关文章

Spring Boot Security OAuth2 实现支持JWT令牌的授权服务器

概要 之前的两篇文章,讲述了Spring Security 结合 OAuth2 .JWT 的使用,这一节要求对 OAuth2.JWT 有了解,若不清楚,先移步到下面两篇提前了解下. Spring Boot Security 整合 OAuth2 设计安全API接口服务 Spring Boot Security 整合 JWT 实现 无状态的分布式API接口 这一篇我们来实现 支持 JWT令牌 的授权服务器. 优点 使用 OAuth2 是向认证服务器申请令牌,客户端拿这令牌访问资源服务服务器,资源服务

Spring Boot 探索系列 - 自动化配置篇

26. Logging Prev  Part IV. Spring Boot features  Next 26. Logging Spring Boot uses Commons Logging for all internal logging, but leaves the underlying log implementation open. Default configurations are provided for Java Util Logging,Log4J, Log4J2 an

学记:为spring boot写一个自动配置

spring boot遵循"约定由于配置"的原则,使用annotation对一些常规的配置项做默认配置,减少或不使用xml配置,让你的项目快速运行起来.spring boot的神奇不是借助代码的生成来实现的,而是通过条件注解来实现的. 自动配置AutoConfiguration是实现spring boot的重要原理,理解AutoConfiguration的运行原理特别重要,自己写一个AutoConfiguration可以加深我们对spring boot的理解. 1.定义Type-saf

Spring Boot Security

Spring Boot Security Spring Boot includes an additional set of tools that can make the application development time a little more faster by reducing its restart time. Security https://docs.spring.io/spring-boot/docs/current/reference/html/boot-featur

spring boot slf4j日记记录配置详解

转 spring boot slf4j日记记录配置详解 2017年12月26日 12:03:34 阅读数:1219 Spring-Boot--日志操作[全局异常捕获消息处理?日志控制台输出+日志文件记录] 最好的演示说明,不是上来就贴配置文件和代码,而是,先来一波配置文件的注释,再来一波代码的测试过程,最后再出个技术在项目中的应用效果,这样的循序渐进的方式,才会让读者更加清楚的理解一项技术是如何运用在项目中的,虽然本篇很简单,几乎不用手写什么代码,但是,比起网上其他人写的同类型的文章来说,我只能

Spring boot security rest basic Authentication example

1. Maven dependency pom.xml <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.0.5.RELEASE</version> <relativePath /> </parent> <depe

Spring Boot 2.0+ 自定义配置类扩展springMVC的功能

在spring boot1.0+,我们可以使用WebMvcConfigurerAdapter来扩展springMVC的功能,其中自定义的拦截器并不会拦截静态资源(js.css等). 在Spring Boot2.0版本中,WebMvcConfigurerAdapter这个类被弃用了. @Deprecated public abstract class WebMvcConfigurerAdapter implements WebMvcConfigurer { 那么我们如何来扩展关于MVC的配置呢?

Spring Boot 部署与服务配置

Spring Boot 其默认是集成web容器的,启动方式由像普通Java程序一样,main函数入口启动.其内置Tomcat容器或Jetty容器,具体由配置来决定(默认Tomcat).当然你也可以将项目打包成war包,放到独立的web容器中(Tomcat.weblogic等等),当然在此之前你要对程序入口做简单调整. 项目构建我们使用Maven或Gradle,这将使项目依赖.jar包管理.以及打包部署变的非常方便. 一.内嵌 Server 配置 Spring Boot将容器内置后,它通过配置文件

Spring Boot教程30——Tomcat配置

本节的配置方法对Tomcat.Jetty和Undertow等内嵌servlet容器都是通用的. 1.Properties配置Tomcat 关于Tomcat的所有属性都在org.springframework.boot.autoconfigure.web.ServerProperties配置类中做了定义,我们只需在application.properties配置属性做配置即可.通用的Servlet容器配置都以“server”作为前缀,而Tomcat特有配置都以“server.tomcat”作为前缀