我想基于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层处理它?谢谢你的帮助。
答案 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解释了您正在逐步查看的回购项目中构建的项目。