SpringBoot with SpringSecurity

作者: HikariCP | 来源:发表于2017-11-06 02:30 被阅读104次

    在编写 web 应用时。我们经常会对页面进行一系列的安全控制。比如一些页面对没有权限的用户不开放访问权限,此时会令该请求的用户跳转到登录页面。当然要实现访问控制的方法方式多种多样,可以通过过滤器,拦截器,Aop,甚至集成框架来实现。(如:Apache Shiro、Spring Security)


    Cfiguration

    @Configuration
    public class MvcConfig extends WebMvcConfigurerAdapter {
    
        @Override
        public void addViewControllers(ViewControllerRegistry registry) {
            registry.addViewController("/index").setViewName("index");
            registry.addViewController("/").setViewName("index");
            registry.addViewController("/hello").setViewName("hello");
            registry.addViewController("/login").setViewName("login");
        }
    }
    

    index

    <!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>
    <h1>Welcome!</h1>
    
    <p>Click <a th:href="@{/hello}">here</a> to see a greeting.</p>
    </body>
    </html>
    

    home

    <!DOCTYPE html>
    <html lang="en" xmlns:th="http://www.thymeleaf.org">
    <head>
        <meta charset="UTF-8">
        <title>Hello World!</title>
    </head>
    <body>
        <h1 th:inline="text">Hello [[${#httpServletRequest.remoteUser}]]!</h1>
        <form th:action="@{/logout}" method="post">
            <input type="submit" value="注销"/>
        </form>
    </body>
    </html>
    

    login

    <!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}">
        Invalid username and password.
    </div>
    <div th:if="${param.logout}">
        You have been logged out.
    </div>
    <form th:action="@{/login}" method="post">
        <div><label> User Name : <input type="text" name="username"/> </label></div>
        <div><label> Password: <input type="password" name="password"/> </label></div>
        <div><input ty
    </body>
    </html>pe="submit" value="Sign In"/></div>
    </form>
    

    Configuration

    @Configuration
    @EnableWebSecurity // 开启Spring Security的功能
    public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http
                .authorizeRequests()
                    .antMatchers("/", "home").permitAll()
                    .anyRequest().authenticated()
                    .and()
                .formLogin()
                    .loginPage("/login")
                    .permitAll()
                    .and()
                .logout()
                    .permitAll();
        }
    
        @Autowired
        public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
            auth
                .inMemoryAuthentication()
                    .withUser("user").password("passowrd").roles("USER");
        }
    
    }
    
    • WebSecurityConfig类与注释@EnableWebSecurity,使Spring Security的网络安全支持,并提供了Spring MVC的整合。它还扩展WebSecurityConfigurerAdapter和覆盖了一些方法来设置Web安全配置的一些细节。
    • configure(HttpSecurity)方法定义哪些URL路径应该被保护,哪些不应该。具体来说,“/”和“/ home”路径被配置为不需要任何身份验证。所有其他路径必须经过身份验证。
    • 当用户成功登录时,它们将被重定向到先前请求的需要身份验证的页面。有一个自定义的“/登录”页面指定loginPage(),并且每个人都被允许查看它。
    • 对于该configureGlobal(AuthenticationManagerBuilder)方法,它设置了具有单个用户的内存中用户存储。该用户的用户名为“user”,密码为“password”,角色为“USER”。

    可以看到,这个 Thymeleaf 模板只是提供一个表单来捕获一个用户名和密码,并将它们发布到“/ login”。根据配置,Spring Security 提供了一个拦截该请求并验证用户的过滤器。如果用户无法验证,该页面将重定向到“/ login?error”,页面显示相应的错误消息。成功注销后,应用程序将发送到“/ login?logout”,页面显示相应的成功消息。

    到这里,我们启用应用,并访问http://localhost:8080/,可以正常访问。但是访问http://localhost:8080/hello的时候被重定向到了http://localhost:8080/login页面,因为没有登录,用户没有访问权限,通过输入用户名user和密码password进行登录后,跳转到了Hello World页面,再也通过访问http://localhost:8080/login?logout,就可以完成注销操作。

    相关文章

      网友评论

        本文标题:SpringBoot with SpringSecurity

        本文链接:https://www.haomeiwen.com/subject/hojkmxtx.html