![](/img/trans.png)
[英]Spring Boot Security /login authentication with angularJS
[英]Spring Security authentication through custom login with AngularJS
我正在使用AngularJS前端在我的應用程序中為Spring Security創建一個自定義登錄表單。 我很難弄清楚如何處理身份驗證。 我發現的所有教程和示例都在使用JSP,我看到了以下內容:
<form name='loginForm'
action="<c:url value='j_spring_security_check' />" method='POST'>
我想知道在Angular中會是什么。 我的配置已設置為路由到我的自定義登錄頁面:
@Configuration
@EnableWebSecurity
@Order(SecurityProperties.ACCESS_OVERRIDE_ORDER)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth)
throws Exception {
auth.inMemoryAuthentication().withUser("user").password("pass")
.roles("USER");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().anyRequest().authenticated().and().formLogin().loginPage("/login/login.html").permitAll();
}
}
然后我以為我的登錄頁面將在提交用戶名/密碼時調用Angular函數submitCredentials(isValid)
:
<!doctype html>
<html ng-app="app">
<head>
<title>Person Login</title>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js"></script>
<script src="app.js"></script>
</head>
<div class="container">
<body>
<h1>Person Login</h1>
<br>
<div ng-controller="LoginCtrl">
<form class="form-horizontal" name="loginForm" novalidate>
<div class="form-group">
<label class="col-sm-1 control-label">Username</label>
<div class="col-sm-3">
<input class="form-control" name="username" type="text" ng-model="user.username">
</div>
</div>
<div class="form-group">
<label class="col-sm-1 control-label">Password</label>
<div class="col-sm-3">
<input class="form-control" name="password" type="text" ng-model="user.password">
</div>
</div>
<br><br>
<button class="btn btn-primary" ng-click="submitCredentials(loginForm.$valid)">
Submit
</button>
</form>
</div>
</body>
</div>
</html>
然后在控制器中執行以下操作:
angular.module('app').controller('LoginCtrl', function($scope, $location, $http, $routeParams) {
$scope.submitCredentials(isValid) {
if (isValid) {
// do something to authenticate user
}
}
});
我不知道該怎么做。 現在,我將使用內存中的Spring身份驗證作為一個簡單的開始,因此,如果可以通過自定義登錄實現這一點,我會很高興的。 稍后,我想通過檢查數據庫中的憑據來進行身份驗證。
您有兩種選擇:
這種方法允許您通過表單和<input type="submit">
進行POST請求,從而刷新頁面。 使用這種方法,服務器將為您提供帶有cookie的會話ID,並且將對每個下一個請求進行身份驗證(瀏覽器將自動向每個請求添加會話ID)。
在這種方法中,您將創建自定義AuthenticationFilter
,它將從用戶(例如,從json或xml)獲取憑據並進行身份驗證。 通過此“登錄”請求,您還應該提供一個令牌,該令牌將替代會話ID(cookie)。 您必須在每個下一個請求中添加此令牌,以便服務器可以解析用戶(在標頭,查詢參數,路徑參數中)。
我建議閱讀這篇文章https://spring.io/guides/tutorials/spring-security-and-angular-js/ 。 它應該消除許多疑問。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.