Sto implementando una pagina di accesso AngularJS personalizzata per Spring Security e sto riscontrando problemi di autenticazione.Avvio a molla e sicurezza con pagina di login AngularJS personalizzata
Sto seguendo questo tutorial/esempio, e il loro esempio funziona bene a livello locale: https://github.com/dsyer/spring-security-angular/tree/master/single
Tuttavia, quando provo ad implementare questo me stesso, io non sono in grado di autenticare, e io non sono sicuro dove il mio errore è
Un POST viene creato per/login con credenziali, (il curl è identico all'esempio) e ricevo un 302 Found con un reindirizzamento su GET/login /, che restituisce un 404 non trovato.
Quando tenta di registrare a/login, la primavera non genera log di debug, quindi non sono sicuro di come si sta servendo il 302.
Il mio codice può essere trovato qui: https://github.com/AndrewBell/spring-angular-starter/tree/master
cambiamenti degni di nota (e molto probabilmente la fonte dei miei problemi):
struttura file cambia
Utilizzando rigorosamente angolare (No jQuery) - che si traduce in una funzione diversa necessario per effettuare la richiesta POST
Utilizzando scrigno invece di wro4j
codice angolare styling/scoping
Molti correlate Le domande di Spring Security suggeriscono che la richiesta POST è formattata in modo errato, ma la mia sembra essere la stessa dell'esempio (almeno quando copio in curl in chrome dev console). Altri suggeriscono l'implementazione di provider di autorizzazione personalizzati, ma non è necessario nell'esempio, quindi sono perplesso su quale sia la differenza tra il mio e l'esempio. Aiutami Stack Exchange, sei la mia unica speranza.
strumenti di sviluppo: imgurDOTcom/a/B2KmV
codice rilevante:
login.js
'use strict';
angular
.module('webApp')
.controller('LoginCtrl', ['$root`enter code here`Scope', '$scope', '$http', '$location', '$route', function($rootScope, $scope, $http, $location, $route) {
console.log("LoginCtrl created.");
var vm = this;
vm.credentials = {
username: "",
password: ""
};
//vm.login = login;
$scope.tab = function(route) {
return $route.current && route === $route.current.controller;
};
var authenticate = function(callback) {
$http.get('user').success(function(data) {
console.log("/user success: " + JSON.stringify(data));
if (data.name) {
console.log("And Authenticated!");
$rootScope.authenticated = true;
} else {
console.log("But received invalid data.");
$rootScope.authenticated = false;
}
callback && callback();
}).error(function(response) {
console.log("/user failure." + JSON.stringify(response));
$rootScope.authenticated = false;
callback && callback();
});
};
authenticate();
$scope.login = function() {
var data2 = 'username=' + encodeURIComponent(vm.credentials.username) +
'&password=' + encodeURIComponent(vm.credentials.password);
$http.post('login', data2, {
headers : {
'Content-Type': 'application/x-www-form-urlencoded'
}
}).success(function() {
authenticate(function() {
if ($rootScope.authenticated) {
console.log("Login succeeded");
$location.path("/");
$scope.error = false;
$rootScope.authenticated = true;
} else {
console.log("Login failed with redirect");
$location.path("/login");
$scope.error = true;
$rootScope.authenticated = false;
}
});
}).error(function() {
console.log("Login failed");
$location.path("/login");
$scope.error = true;
$rootScope.authenticated = false;
})
};
$scope.logout = function() {
$http.post('logout', {}).success(function() {
$rootScope.authenticated = false;
$location.path("/");
}).error(function() {
console.log("Logout failed");
$rootScope.authenticated = false;
});
}
}]);
application.java
package com.recursivechaos.springangularstarter;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.security.SecurityProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.csrf.CsrfFilter;
import org.springframework.security.web.csrf.CsrfToken;
import org.springframework.security.web.csrf.CsrfTokenRepository;
import org.springframework.security.web.csrf.HttpSessionCsrfTokenRepository;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.filter.OncePerRequestFilter;
import org.springframework.web.util.WebUtils;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.security.Principal;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
@SpringBootApplication
@RestController
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@RequestMapping("/user")
public Principal user(Principal user) {
return user;
}
@RequestMapping("/resource")
public Map<String, Object> home() {
Map<String, Object> model = new HashMap<>();
model.put("id", UUID.randomUUID().toString());
model.put("content", "Hello World");
return model;
}
@Configuration
@Order(SecurityProperties.ACCESS_OVERRIDE_ORDER)
protected static class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.
formLogin().
//loginPage("/#/login").
and().
logout().
and().
authorizeRequests().
antMatchers("/index.html", "/home/**", "/login/**", "/bower_components/**", "/", "/main.js", "/login/", "/navigation/**","/login","login/","/login.html").
permitAll().
anyRequest().
authenticated().
and().
csrf().
csrfTokenRepository(csrfTokenRepository()).
and().
addFilterAfter(csrfHeaderFilter(), CsrfFilter.class);
}
private Filter csrfHeaderFilter() {
return new OncePerRequestFilter() {
@Override
protected void doFilterInternal(HttpServletRequest request,
HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
CsrfToken csrf = (CsrfToken) request.getAttribute(CsrfToken.class
.getName());
if (csrf != null) {
Cookie cookie = WebUtils.getCookie(request, "XSRF-TOKEN");
String token = csrf.getToken();
if (cookie == null || token != null
&& !token.equals(cookie.getValue())) {
cookie = new Cookie("XSRF-TOKEN", token);
cookie.setPath("/");
response.addCookie(cookie);
}
}
filterChain.doFilter(request, response);
}
};
}
private CsrfTokenRepository csrfTokenRepository() {
HttpSessionCsrfTokenRepository repository = new HttpSessionCsrfTokenRepository();
repository.setHeaderName("X-XSRF-TOKEN");
return repository;
}
}
}
Se vieni reindirizzato a/login che significa che non sei autenticato (ma non dovrebbe essere un 404 quindi è strano). È possibile attivare la registrazione di debug per 'org.springframework.security' per ottenere informazioni più dettagliate sulla decisione di accesso (mi aspetto che le credenziali fossero in qualche modo cattive), ad es. imposta 'logging.level.org.springframework.security = DEBUG' in' applicazione. [proprietà, yml] '. –
@DaveSyer Guardando attraverso i log, non riesco a vedere nemmeno un POST to/login Come posso verificare che Spring gestisca POST/login? http://pastebin.com/GeUkCUvg – Andrew
Sembra che si tratti di un problema di percorso (o forse di un ambito), poiché sono riuscito a estrarre il progetto "singolo" dagli esempi di github, rimuovere il wro4j e sostituirlo con il seguente scrigno di dipendenze: "angolare": "^ 1.3.0", "angolare-risorsa": "^ 1.3.0", "angolare-bootstrap": "~ 0.12.0", "bootstrap-css-only": "~ 3.3.2", "angolare-route": "~ 1.3.11" E utilizzando ... var req = 'username =' + ($ scope.credentials.username) + = '+ ($ scope.credentials.password); $ http.post ('login', req .... sembra funzionare bene – Andrew