5

Problembeschreibung: Meine UI-App läuft auf 9000 Port (grunt Projekt) und meine Server Seite Spring Boot-Projekt auf 8421 Port ausgeführt. Ich bin in der Lage, alle URLs von meiner UI-App aus zu treffen, außer beim Anmelden und Abmelden. Bitte lassen Sie mich wissen, wie kann ich Spring Security Login und Logout mit CORS konfigurieren.AngularJS Spring Security Login/Logout mit Cross-Origin Resource Sharing (CORS)

App.js

$scope.login = function() { 
     $http.post('http://localhost:8421/login', $.param($scope.credentials), { 
      headers : { 
      'content-type' : 'application/x-www-form-urlencoded' 
      } 
     }).success(function() { 
      console.log('login success'); 
      }); 
     }).error(function() { 
      console.log('login error'); 
     }); 
     }; 

SecurityConfiguration.java

public class SecurityConfiguration extends WebSecurityConfigurerAdapter { 

@Override 
    protected void configure(HttpSecurity http) throws Exception { 

     http.addFilterBefore(new SimpleCORSFilter(), ChannelProcessingFilter.class) 
     .authorizeRequests().antMatchers("/rest/**").permitAll() 
     .and().logout().logoutRequestMatcher(new AntPathRequestMatcher("/logout")) 
     .logoutSuccessUrl("/index.html")   
     .and().exceptionHandling().authenticationEntryPoint(authenticationEntryPoint)  
     .and().formLogin().successHandler(authenticationSuccessHandler) 
     .and().formLogin().failureHandler(authenticationFailureHandler)   
     .and().csrf().disable(); 
    } 

@Autowired 
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { 

     auth.userDetailsService(userDetailsService).passwordEncoder(new BCryptPasswordEncoder()); 
    } 
} 

SimpleCORSFilter.java

public class SimpleCORSFilter implements Filter { 
@Override 
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { 
     HttpServletRequest request = (HttpServletRequest) req; 
     HttpServletResponse response = (HttpServletResponse) res; 

     response.setHeader("Access-Control-Allow-Origin", "*"); 
     response.addHeader("Access-Control-Allow-Credentials", "true"); 
     response.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS, DELETE"); 
     response.setHeader("Access-Control-Max-Age", "3600"); 
     response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); 

     chain.doFilter(req, res); 
    } 

    @Override 
    public void init(FilterConfig filterConfig) { 

    } 

    @Override 
    public void destroy() { 

    } 
} 

login.html

<form> 
<div class="rb-form-group" ng-class="{ 'has-error' : userForm.username.$invalid && !userForm.username.$pristine }"> 
      <input type="text" name="username" class="form-control" ng-model="credentials.username" placeholder="enter your username" required> 
     </div> 

     <!-- PASSWORD --> 
     <div class="rb-form-group" ng-class="{ 'has-error' : userForm.password.$invalid && !userForm.password.$pristine }"> 
      <input type="password" name="password" class="form-control" ng-model="credentials.password" placeholder="enter your password" required>   
     </div> 

     <div class="rb-form-group"> 
      <button class="btn btn-primary btn-block" ng-disabled="userForm.$invalid" ng-click="login()">Login</button>   
     </div> 
</form> 

Vielen Dank im Voraus

Netzwerk log

Remote Address:[::1]:8421 
Request URL:http://localhost:8421/login 
Request Method:POST 
Status Code:200 OK 
Response Headers 
view source 
Access-Control-Allow-Credentials:true 
Access-Control-Allow-Credentials:true 
Access-Control-Allow-Headers:Origin, X-Requested-With, Content-Type, Accept 
Access-Control-Allow-Methods:POST, GET, PUT, OPTIONS, DELETE 
Access-Control-Allow-Origin:* 
Access-Control-Max-Age:3600 
Cache-Control:no-cache, no-store, max-age=0, must-revalidate 
Content-Length:0 
Date:Tue, 17 Nov 2015 04:01:57 GMT 
Expires:0 
Pragma:no-cache 
Server:Apache-Coyote/1.1 
Set-Cookie:JSESSIONID=D22C05E81D4FC86EA32BD6545F2B37FF; Path=/; HttpOnly 
X-Content-Type-Options:nosniff 
X-Frame-Options:DENY 
X-XSS-Protection:1; mode=block 
Request Headers 
view source 
Accept:application/json, text/plain, */* 
Accept-Encoding:gzip, deflate 
Accept-Language:en-US,en;q=0.8 
Connection:keep-alive 
Content-Length:31 
content-type:application/x-www-form-urlencoded 
Host:localhost:8421 
Origin:http://localhost:9000 
Referer:http://localhost:9000/src/ 
User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.86 Safari/537.36 
+1

Keep it simple und das Frontend in Ihrem Frühjahr Web-Server und verwenden den gleichen Port und Protokoll führen. Wenn Sie wirklich wirklich CORS benutzen müssen, posten Sie bitte die Netzwerkprotokolle. Speziell die Anfrage an den Login-URI (Methoden: OPTION und POST) – Michael

+0

@Michael: Danke für die Antwort. Ich habe meine Frage mit dem Netzwerkprotokoll für die Anmeldung aktualisiert. Bitte schau es dir an. –

+0

Ja, CORS ist notwendig, da wir dieselbe Enterprise-Anwendung für verschiedene Clients erstellen. Also müssen wir alle Dinge entkoppeln. –

Antwort

1

Soweit CORS Problem betroffen ist, fügen Sie bitte authorization und client-security-token auf die wie unten Access-Control-Allow-Headers header.

Dies sollte ordnungsgemäß funktionieren, wenn Ihr CORS-Filter richtig konfiguriert ist!

Für die Verwendung von AJAX-basierten Login im Frühjahr Sicherheit, möchten Sie vielleicht etwas anderen Ansatz folgen. Dies wird hier erklärt:

Hoffe, dass es hilft, können Sie für jede Frage Kommentar!

0

Ich bin dieses Problem auf der AngularJS und Spring-Anwendung getan. Es ist ganz einfach. Fügen Sie einfach den Filter

public class CORSFilter extends OncePerRequestFilter { 

    private final Logger LOG = LoggerFactory.getLogger(CORSFilter.class); 

    @Override 
    protected void doFilterInternal(HttpServletRequest req, HttpServletResponse res, FilterChain chain) throws ServletException, IOException { 
     res.setHeader("Access-Control-Allow-Origin", "*"); 
     res.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS"); 
     res.setHeader("Access-Control-Max-Age", "3600"); 
     res.setHeader("Access-Control-Allow-Headers", "X-PINGOTHER,Content-Type,X-Requested-With,accept,Origin,Access-Control-Request-Method,Access-Control-Request-Headers,Authorization"); 
     res.addHeader("Access-Control-Expose-Headers", "xsrf-token"); 
     if ("OPTIONS".equals(req.getMethod())) { 
     res.setStatus(HttpServletResponse.SC_OK); 
     } else { 
     chain.doFilter(req, res); 
     }   
    } 
} 

Vom Post angularjs spring cross-origin request blocked