【问题标题】:Not able to get rid of user credential request pop up using Spring Security?无法摆脱使用 Spring Security 弹出的用户凭据请求?
【发布时间】:2018-08-09 18:51:10
【问题描述】:

我正在将 Spring Security 集成到我的 Spring MVC 和 Angular 应用程序中。

版本:

Spring Security:4.1.5.RELEASE

Spring MVC:4.2.0.RELEASE

角度:4

集成后,我看到浏览器显示用户名和密码弹出窗口。即使在进行了更改之后,我也无法摆脱弹出窗口并继续以 Angular 自定义登录表单。


首先,我使用的是 http 基本身份验证机制。 为此创建了以下 SecurityConfig.java[更新]

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        // @formatter:on
        auth.inMemoryAuthentication().withUser("user1").password("user1").roles("USER").and().withUser("user2")
                .password("user2").roles("USER").and().withUser("admin").password("admin").roles("ADMIN");
        // @formatter:off

    }

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

}

对于资源和路径解析,创建于 ServletContextConfiguration.java 之后。

@Configuration
@EnableWebMvc
public class ServletContextConfiguration extends WebMvcConfigurerAdapter {

    @Override
    public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
         configurer.favorPathExtension(true).ignoreAcceptHeader(true).useJaf(false)
         .defaultContentType(MediaType.APPLICATION_JSON).mediaType("html",
         MediaType.TEXT_HTML)
         .mediaType("xml", MediaType.APPLICATION_XML).mediaType("json",
         MediaType.APPLICATION_JSON);
    }

    @Override
    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
        configurer.enable();
    }

    @Bean(name = "contentNegotiatingViewResolver")
    public ViewResolver getContentNegotiatingViewResolver(ContentNegotiationManager manager) {
        ContentNegotiatingViewResolver resolver = new ContentNegotiatingViewResolver();
        resolver.setContentNegotiationManager(manager);
        return resolver;
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/**").addResourceLocations("/dist/").resourceChain(true)
                .addResolver(new PathResourceResolver());
    }

}

以下是我的web.xml

<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
    version="3.0">
    <display-name>Archetype Created Web Application</display-name>

    <!-- Creates the Spring Container shared by all Servlets and Filters -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <!-- Processes application requests -->
    <servlet>
        <servlet-name>appServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/applicationContext.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>appServlet</servlet-name>
        <url-pattern>/</url-pattern>
        <url-pattern>*.html</url-pattern>
        <url-pattern>/index.html</url-pattern>
    </servlet-mapping>

    <welcome-file-list>
        <welcome-file>index.html</welcome-file>
    </welcome-file-list>


    <!-- Spring Security -->
    <filter>
        <filter-name>springSecurityFilterChain</filter-name>
        <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>springSecurityFilterChain</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

</web-app>

我正在使用 weblogic server 来部署 war 文件。

weblogic.xml

<?xml version="1.0" encoding="UTF-8"?>
<wls:weblogic-web-app
        xmlns:wls="http://xmlns.oracle.com/weblogic/weblogic-web-app"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://xmlns.oracle.com/weblogic/weblogic-web-app
        http://xmlns.oracle.com/weblogic/weblogic-web-app/1.4/weblogic-web-app.xsd">
    <wls:context-root>/</wls:context-root>
    <wls:container-descriptor>
        <wls:prefer-application-packages>
            <wls:package-name>org.slf4j.*</wls:package-name>
            <wls:package-name>org.springframework.*</wls:package-name>
            <wls:package-name>org.springframework.web.servlet.view.*</wls:package-name>
            <wls:package-name>oracle.core.*</wls:package-name>
            <wls:package-name>oracle.jdbc.*</wls:package-name>
            <wls:package-name>oracle.net.*</wls:package-name>
            <wls:package-name>oracle.sql.*</wls:package-name>
            <wls:package-name>oracle.security.*</wls:package-name>
            <wls:package-name>org.hibernate.*</wls:package-name>
            <wls:package-name>com.fasterxml.*</wls:package-name>
        </wls:prefer-application-packages>
    </wls:container-descriptor>
</wls:weblogic-web-app>

角度变化:

app.module.ts中引入了http拦截器来注入http头X-Requested-With建议here

import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { RouterModule, Routes } from '@angular/router';
import { NgModule } from '@angular/core';
import { Injectable } from '@angular/core';
import {
  HttpEvent, HttpInterceptor, HttpHandler, HttpRequest, HTTP_INTERCEPTORS
} from '@angular/common/http';
import { Observable } from 'rxjs/Observable';

import { AppComponent } from './app.component';
import { StoreComponent } from './components/store/store.component';
import { StoreService } from './services/store.service';
import { LoginComponent } from './components/login/login.component';
import { LogoutComponent } from './components/logout/logout.component';

@Injectable()
export class XhrInterceptor implements HttpInterceptor {

  intercept(req: HttpRequest<any>, next: HttpHandler) {
    const xhr = req.clone({
      headers: req.headers.set('X-Requested-With', 'XMLHttpRequest')
    });
    console.log(">>>>>>>>>>HttpRequest intercepted...");
    return next.handle(xhr);
  }
}

const appRoutes: Routes = [
  { path:'', pathMatch: 'full', redirectTo: 'login' },
  { path: 'login', component: LoginComponent},
  { path: 'logout', component: LogoutComponent },
  { path: 'store', component: StoreComponent }
]

@NgModule({
  declarations: [
    AppComponent,
    StoreComponent,
    LoginComponent,
    LogoutComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
    RouterModule.forRoot(appRoutes)
  ],
  providers: [ StoreService, { provide: HTTP_INTERCEPTORS, useClass: XhrInterceptor, multi: true } ],
  bootstrap: [ AppComponent ]
})
export class AppModule { }

由于某种原因,我仍然可以看到从浏览器弹出的默认用户名和密码。 在 Web 控制台中,我看不到 X-Requested-With 标头。另外,我没有看到在 http 请求被拦截时应该打印的控制台日志。

我认为,请求可能没有到达 Angular 客户端,并且服务器端发生了错误。 这里可能缺少什么?


更新:

按照建议,我已将 http.basic() 请求替换为 http.authorizeRequests()。现在,/login 请求不会显示弹出窗口。但是一旦我尝试通过调用/authenticate 在我的自定义登录页面中提交用户凭据后,我再次看到弹出窗口:(

这里可能缺少什么。

请澄清。

谢谢。

【问题讨论】:

  • 您能否解决您的问题。我也有同样的问题。如果你能帮忙...谢谢-Sudhir

标签: java spring angular spring-security


【解决方案1】:

这是由于您的配置中的http.httpBasic(),它应该是http.authorizeRequests()

【讨论】:

    【解决方案2】:

    您仍在使用 spring security 的 http 基本身份验证,这就是为什么它显示基本身份验证弹出,不要使用它,使用 http.autherizeRequest() 并使用 machers 允许您的登录 url。 并在 routemodule 中为登录组件定义相同的路径。它会起作用的。

    【讨论】:

    • 但是在 Spring Security 教程 spring.io/guides/tutorials/spring-security-and-angular-js/… 中,我不明白他为什么谈到 http.basic() 并避免()在客户端弹出引入 X-Requested-With 标头,这在这里没有任何区别。
    • 可能是带有标头的 x-request 也可以,但我在关注这个官方文档时也遇到了同样的问题。我按照其他文档在 spring security 中使用 angular 自定义登录表单,并且有效。
    猜你喜欢
    • 2014-01-29
    • 2021-04-03
    • 1970-01-01
    • 2015-08-31
    • 2013-12-28
    • 2018-10-18
    • 2018-12-13
    • 2019-05-21
    • 2013-06-25
    相关资源
    最近更新 更多