SpringBoot-注销登录配置(续HttpSecurity)

本文主要探讨了SpringBoot中如何进行注销登录的配置,通过HttpSecurity进行设置,并通过Postman进行了实际的测试验证。
摘要由CSDN通过智能技术生成

注销登录配置

package org.akk.security.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AccountExpiredException;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.CredentialsContainer;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Bean
    PasswordEncoder passwordEncoder() {
        return NoOpPasswordEncoder.getInstance();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
                .withUser("uuc").password("123").roles("admin")
                .and()
                .withUser("akk").password("123").roles("user");
    }


    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/admin/**").hasRole("admin")
                .antMatchers("user/**").hasAnyRole("admin", "user")
                .anyRequest().authenticated()
                .and()
                .formLogin()
                //这里就是处理登录的url,
                .loginProcessingUrl("/doLogin")
                //跳转的登录界面
                .loginPage("/login")
                .usernameParameter("name")
                .passwordParameter("passwd")
                .successHandler(new AuthenticationSuccessHandler() {
                    //authentication中保存了登陆成功的用户信息
                    @Override
                    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
                        httpServletResponse.setContentType("application/json;charset = utf-8");
                        PrintWriter out = httpServletResponse.getWriter();
                        Map<String, Object> map = new HashMap<>();
                        map.put("status", 200);
                        map.put("msg", authentication.getPrincipal());
                        out.write(new ObjectMapper().writeValueAsString(map));
                        out.flush();
                        out.close();
                    }
                })
                .failureHandler(new AuthenticationFailureHandler() {
                    @Override
                    public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
                        httpServletResponse.setContentType("application/json;charset = utf-8");
                        PrintWriter out = httpServletResponse.getWriter();
                        Map<String, Object> map = new HashMap<>();
                        map.put("status", 401);
                        if (e instanceof LockedException) {
                            map.put("msg", "账户被锁定,登陆失败");
                        } else if (e instanceof BadCredentialsException) {
                            map.put("msg", "用户名或者密码输入错误,登陆失败");
                        } else if (e instanceof DisabledException) {
                            map.put("msg", "账户被禁用,登陆失败");
                        } else if (e instanceof AccountExpiredException) {
                            map.put("msg", "账户过期,登陆失败");
                        } else if (e instanceof CredentialsContainer) {
                            map.put("msg", "密码过期,登陆失败");
                        }else{
                            map.put("msg","登陆失败");
                        }
                        out.write(new ObjectMapper().writeValueAsString(map));
                        out.flush();
                        out.close();
                    }
                })
                .permitAll()
                .and()
                //配置logout进行注销
                .logout()
                //请求地址
                .logoutUrl("/logout")
                .logoutSuccessHandler(new LogoutSuccessHandler() {
                    @Override
                    public void onLogoutSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
                        httpServletResponse.setContentType("application/json;charset = utf-8");
                        PrintWriter out = httpServletResponse.getWriter();
                        Map<String, Object> map = new HashMap<>();
                        map.put("status", 200);
                        map.put("msg", "注销登录成功");
                        out.write(new ObjectMapper().writeValueAsString(map));
                        out.flush();
                        out.close();
                    }
                })
                .and()
                .csrf().disable();
    }
}

postman测试:
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
springboot配置springsecurity的登陆和注销功能,需要进行如下步骤: 1. 添加springsecurity依赖 在pom.xml文件中添加springsecurity依赖: ``` <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> ``` 2. 配置springsecurity 在应用程序的配置类中添加@EnableWebSecurity注解,开启springsecurity配置功能,并继承WebSecurityConfigurerAdapter类,重写configure方法,进行springsecurity配置: ``` @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .antMatchers("/login").permitAll() .antMatchers("/admin/**").hasRole("ADMIN") .anyRequest().authenticated() .and() .formLogin() .loginPage("/login") .defaultSuccessUrl("/home") .failureUrl("/login?error=true") .permitAll() .and() .logout() .logoutUrl("/logout") .logoutSuccessUrl("/login") .permitAll() .and() .csrf().disable(); } @Autowired public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication() .withUser("user").password("{noop}password").roles("USER") .and() .withUser("admin").password("{noop}password").roles("ADMIN"); } } ``` 上述代码中,我们使用了inMemoryAuthentication()方法来配置用户信息。其中,用户"user"的密码为"password",拥有"USER"角色;用户"admin"的密码为"password",拥有"ADMIN"角色。 3. 创建登陆和注销页面 在resources/templates目录下创建login.html和home.html两个页面,分别用于登陆和注销后跳转的页面。 login.html页面示例: ``` <!DOCTYPE html> <html> <head> <title>Login</title> </head> <body> <h2>Login</h2> <form th:action="@{/login}" method="post"> <div> <label>Username:</label> <input type="text" name="username"/> </div> <div> <label>Password:</label> <input type="password" name="password"/> </div> <div> <button type="submit">Login</button> </div> <div th:if="${param.error}"> Invalid username and password. </div> </form> </body> </html> ``` home.html页面示例: ``` <!DOCTYPE html> <html> <head> <title>Home</title> </head> <body> <h2>Welcome!</h2> <p>You have successfully logged in.</p> <form th:action="@{/logout}" method="post"> <button type="submit">Logout</button> </form> </body> </html> ``` 4. 运行应用程序 现在,我们可以运行应用程序,打开浏览器访问http://localhost:8080/login,输入用户信息进行登陆。登陆成功后,将跳转到http://localhost:8080/home页面,页面中将显示"Welcome! You have successfully logged in."的欢迎信息。在home.html页面中,我们可以通过"Logout"按钮注销用户,将跳转回登陆页面。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值