Springboot 使用Security完成登录

1.编写获取用户信息的接口

2.对mapper数据层接口进行实现

3.编写登陆业务层

4.编写登陆的逻辑

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Resource
    LoginServiceImpl loginServiceImpl;

    @Bean
    PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder(10);
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(loginServiceImpl);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        /*
        * 这里允许所有请求经过
        *
        * */
//        http.authorizeRequests()
//                .anyRequest().permitAll().and().logout().permitAll()
//                .and().csrf().disable();
        //暂时把跨域攻击关了 不然不发POST请求

        http.authorizeRequests()
                .antMatchers("/api/**").access("hasRole('ROLE_USER') or hasRole('ROLE_ADMIN')")
                .antMatchers("/Adminapi/**").hasRole("admin")
                .antMatchers("/Dbapi/**").hasRole("dba")
                .antMatchers("/registered/**").permitAll()
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .loginProcessingUrl("/login")
                .usernameParameter("username")
                .passwordParameter("password")
                .successHandler(new NokiaAuthenticationSuccessHandler())
                .failureHandler(new NokiaAuthenticationFailureHandler())
                .permitAll()
                .and()
                .exceptionHandling()
                .authenticationEntryPoint(new NokiaAuthenticationEntryPoint())
                .and()
                .csrf().disable();
    }
}

5.实现三个控制器 对登陆成功 失败 未验证三种情况的返回值进行处理

 

Spring Boot整合Security实现登录验证拦截器,可以通过以下步骤完成: 1.添加Security依赖 在pom.xml文件中添加以下依赖: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> ``` 2.配置Security 在配置类中添加@EnableWebSecurity注解,并继承WebSecurityConfigurerAdapter类,实现configure()方法,配置Security相关信息,如登录页面、成功页面、失败页面等: ```java @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .antMatchers("/login").permitAll() .anyRequest().authenticated() .and() .formLogin() .loginPage("/login") .defaultSuccessUrl("/success") .failureUrl("/error") .permitAll() .and() .logout() .logoutSuccessUrl("/login") .permitAll(); } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication() .withUser("user").password("password").roles("USER"); } } ``` 3.添加登录页面 在templates目录下添加login.html页面,实现用户登录表单,如下所示: ```html <!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <title>Login Page</title> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> </head> <body> <h1>Login Page</h1> <div th:if="${param.error}"> Invalid username and password. </div> <div th:if="${param.logout}"> You have been logged out. </div> <form th:action="@{/login}" method="post"> <div> <label for="username">Username:</label> <input type="text" id="username" name="username" /> </div> <div> <label for="password">Password:</label> <input type="password" id="password" name="password" /> </div> <div> <input type="submit" value="Login" /> </div> </form> </body> </html> ``` 4.添加成功页面和失败页面 在templates目录下添加success.html和error.html页面,用于显示用户登录成功和失败的信息。 5.添加拦截器 在Controller中添加拦截器,实现对指定的URL进行拦截,如下所示: ```java @Controller public class HomeController { @GetMapping("/") public String home() { return "home"; } @GetMapping("/login") public String login() { return "login"; } @GetMapping("/success") public String success() { return "success"; } @GetMapping("/error") public String error() { return "error"; } @GetMapping("/admin") public String admin() { return "admin"; } } ``` 6.测试登录验证拦截器 启动应用,通过浏览器访问http://localhost:8080/admin,应该会自动跳转到登录页面,输入用户名和密码,登录成功后会跳转到成功页面,否则会跳转到失败页面。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值