春季会话登录

时间:2016-11-25 10:11:01

标签: java spring session

我想基于this example构建一个Web应用程序。

我从这个例子中理解的是你构建了2个应用程序:
包含网页的UI应用程序,您可以在其中登录以获取使用令牌请求数据的令牌和资源应用程序。

我的问题是登录检查在哪里?
application.yml 文件为用户“用户

定义密码“密码
security:
  user:
    password: password

UIApplication.java 文件或任何其他文件中都没有提及此文件:

@SpringBootApplication
@RestController
public class UiApplication {

    public static void main(String[] args) {
        SpringApplication.run(UiApplication.class, args);
    }

    @Configuration
    @Order(SecurityProperties.ACCESS_OVERRIDE_ORDER)
    protected static class SecurityConfiguration extends WebSecurityConfigurerAdapter {

        @Override
        protected void configure(HttpSecurity http) throws Exception {
            // @formatter:off
            http
                .httpBasic().and()
                .logout().and()
                .authorizeRequests()
                    .antMatchers("/index.html", "/pages/home.html", "/pages/login.html", "/").permitAll()
                    .anyRequest().authenticated().and()
                .csrf()
                    .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse());
            // @formatter:on
        }
    }

    @RequestMapping("/user")
    public Principal user(Principal user) {
        return user;
    }

    @RequestMapping("/token")
    public Map<String,String> token(HttpSession session) {
        return Collections.singletonMap("token", session.getId());
    }

}

然而它的工作原理是:当我使用“user”和“password”登录成功时,当我使用不同的凭据时,它会失败。
是否有一些高级Spring层处理它?谢谢你的帮助。

1 个答案:

答案 0 :(得分:0)

这是你选择的一个令人困惑的例子,因为它使用Angular进行登录。所以它使用AngularJS发送请求。

要分解,首先让我们看看login.html页面:

<form role="form" ng-submit="controller.login()">

因此,当我们提交时,我们需要controller.login()方法调用,这在hello.js文件中定义。

}).when('/login', {
        templateUrl : 'login.html',
        controller : 'navigation',
        controllerAs : 'controller'

此处,我们委托发送给/login的请求并将其映射到我们的navigation控制器。如果您继续使用hello.js脚本,则会看到以下内容:

.controller('navigation',
    ...
    var authenticate = function(credentials, callback) {

        var headers = credentials ? {
            authorization : "Basic "
                    + btoa(credentials.username + ":"
                            + credentials.password)
        } : {};

        $http.get('user', {
                ...

在这里,我们使用向GET发出/user请求。如果您查看controller,您会看到有一个用户原则被返回,然后根据凭据进行检查。

控制器需要传递用户原则以进行验证,该原则正在$http请求的headers部分中构建。

如果您是Spring Security的新手,我建议使用this example,并希望从更加面向Java和简单的事情开始。

修改

还应该注意,用户对象是由Spring application.yml创建的,正如您所说,它由以下内容组成:

security:
  user:
    password: password

这相当于:

security.user.password="password"

可以找到对application.yml附录的引用here

所以从本质上讲,yml文件正在创建一个具有给定密码的User,可以通过Principle检索。 Spring撰写的Take a look at the huge guide解释了您正在逐步查看的回购项目中构建的项目。

相关问题