zoukankan      html  css  js  c++  java
  • 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

      

     

  • 相关阅读:
    什么是接口测试?怎样做接口测试?
    python下批量执行多条py文件的方法
    Jmeter运行报错software caused connection abort:recv failed
    性能测试一般容易出现瓶颈点
    性能测试流程规范(较好文档)
    Jmeter代理录制获取登录参数_移动端设置代理
    Http请求与WebSocket请求区别(WebSocket协议简析)
    JSONObject方法提取响应数据中的值
    Jmeter学习资料、控件下载地址大全
    图解IntelliJ IDEA 13版本对Android SQLite数据库的支持
  • 原文地址:https://www.cnblogs.com/galibujianbusana/p/11336940.html
Copyright © 2011-2022 走看看