zoukankan      html  css  js  c++  java
  • Spring Boot (22) Spring Security

    除了使用拦截器、过滤器实现对没有权限访问的页面跳转到登陆页外,还可以通过框架实现:Spring Security。

    使用Spring Security 完成登陆验证:

    1.pom.xml添加依赖

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

    2.创建spring security的配置类WebSecurityConfig.java

    @Configuration
    //开启spring security
    @EnableWebSecurity
    public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http
                    //通过authorizeRequests定义哪些url需要被保护,哪些不被保护
                    .authorizeRequests()
                    // / 和 /users/ 可以访问
                    .antMatchers("/", "/users/").permitAll()
                    .anyRequest().authenticated()
                    .and()
                    .formLogin()
                    //需要登陆时 转到的登陆页面
                    .loginPage("/login")
                    .permitAll()
                    .and()
                    .logout()
                    .permitAll();
        }
    
        @Autowired
        //在内存中创建一个用户,该用户的名称为user1,密码为123 用户角色为Admin
        public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
            //从内存中获取
            auth
                    .inMemoryAuthentication()
                    .passwordEncoder(new BCryptPasswordEncoder())
                    .withUser("user1")
                    .password(new BCryptPasswordEncoder().encode("123"))
                    .roles("Admin");
        }
    }

    新增登陆请求与页面

    LoginController.java

    @Controller
    public class LoginController {
    
        @RequestMapping("/login")
        public String login(){
            return "login";
        }
    
    }

    resources/templates/login.html

    <!DOCTYPE html>
    <html xmlns="http://www.w3.org/1999/xhtml"
          xmlns:th="http://www.thymeleaf.org"
          xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
    <head>
        <title>Spring Security Example </title>
    </head>
    <body>
    <div th:if="${param.error}">
        用户名或密码错
    </div>
    <div th:if="${param.logout}">
        您已注销成功
    </div>
    <form th:action="@{/login}" method="post">
        <div><label> 用户名 : <input type="text" name="username"/> </label></div>
        <div><label> 密  码 : <input type="password" name="password"/> </label></div>
        <div><input type="submit" value="登录"/></div>
    </form>
    </body>
    </html>

    测试:访问 /users/ 没问题 ,访问/users/2 跳转到login.html页 , 输入 user1 pass:123 则登陆成功,在访问/users/2 没有问题。

  • 相关阅读:
    Android安全机制
    service不死之身
    图片加载机制比较
    handler机制面试
    SharedPreferences封装类
    文字太长自动缩小
    ANR
    onCreate源码分析
    线程池的启动策略
    Oauth认证协议
  • 原文地址:https://www.cnblogs.com/baidawei/p/9122858.html
Copyright © 2011-2022 走看看