簡體   English   中英

SpringBoot 安全性:在 Angular 8 中顯示登錄頁面時出現問題

[英]SpringBoot security : Issue while showing login page in Angular 8

我正在為我的項目實現登錄功能。 在前端,我使用的是 Angular 8。我以這種方式實現,因此 Angular 8 和 Springboot 運行在相同的端口 8090 上。

我有路由

const routes: Routes = [
  { path: '', component: EmployeeComponent,canActivate:[AuthGaurdService] },
  { path: 'addemployee', component: AddEmployeeComponent,canActivate:[AuthGaurdService]},
  { path: 'login', component: LoginComponent },
  { path: 'logout', component: LogoutComponent,canActivate:[AuthGaurdService] },
];

Java 方面:我已經將其設置為允許所有 /login 請求

網絡安全配置

 @Override
    protected void configure(HttpSecurity httpSecurity)
        throws Exception
    {
        // We don't need CSRF for this example
        httpSecurity.csrf().disable()
            // dont authenticate this particular request
            .authorizeRequests().antMatchers("/login").permitAll()
            .antMatchers(HttpMethod.OPTIONS, "/**").permitAll().anyRequest().authenticated().and().
            // make sure we use stateless session; session won't be used to
            // store user's state.
            exceptionHandling().authenticationEntryPoint(jwtAuthenticationEntryPoint).and()
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
        // Add a filter to validate the tokens with every request
        httpSecurity.addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class);
    }
}

但仍然在調用 localhost:8090/login 時,我正面臨瀏覽器

白標錯誤頁面 此應用程序沒有明確的 /error 映射,因此您將其視為后備。

2 月 26 日星期三 14:42:50 IST 2020 出現意外錯誤(類型 = 未找到,狀態 = 404)。 沒有可用的消息

在后端,我面對

2020-02-26 14:30:44.045 WARN 5184 --- [nio-8090-exec-1] org.freelancing.utils.JwtRequestFilter :JWT 令牌不以承載字符串開頭 2020-02-26 14:42:49.94 WARN 5184 --- [nio-8090-exec-3] org.freelancing.utils.JwtRequestFilter :JWT 令牌不以 Bearer String 2020-02-26 14:42:51.287 WARN 5184 --- [nio-8090- exec-4] org.freelancing.utils.JwtRequestFilter :JWT 令牌不以承載字符串開頭

我認為它在這個塊中進行

@Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
                                    FilterChain chain)
        throws ServletException,
        IOException
    {
        final String requestTokenHeader = request.getHeader("Authorization");
        String username = null;
        String jwtToken = null;
        // JWT Token is in the form "Bearer token". Remove Bearer word and get
        // only the Token
        if (requestTokenHeader != null && requestTokenHeader.startsWith("Bearer "))
        {
            jwtToken = requestTokenHeader.substring(7);
            try
            {
                username = jwtTokenUtil.getUsernameFromToken(jwtToken);
            }
            catch (IllegalArgumentException e)
            {
                System.out.println("Unable to get JWT Token");
            }
            catch (ExpiredJwtException e)
            {
                System.out.println("JWT Token has expired");
            }
        }
        else
        {
            logger.warn("JWT Token does not begin with Bearer String");
        }
        // Once we get the token validate it.
        if (username != null && SecurityContextHolder.getContext().getAuthentication() == null)
        {
            UserDetails userDetails = this.jwtUserDetailsService.loadUserByUsername(username);
            // if token is valid configure Spring Security to manually set
            // authentication
            if (jwtTokenUtil.validateToken(jwtToken, userDetails))
            {
                UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken =
                    new UsernamePasswordAuthenticationToken(userDetails, null,
                                                            userDetails.getAuthorities());
                usernamePasswordAuthenticationToken
                    .setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                // After setting the Authentication in the context, we specify
                // that the current user is authenticated. So it passes the
                // Spring Security Configurations successfully.
                SecurityContextHolder.getContext()
                    .setAuthentication(usernamePasswordAuthenticationToken);
            }
        }
        chain.doFilter(request, response);
    }

我需要的是呈現登錄頁面,然后獲取憑據並創建標題。但即使在點擊 localhost:8090/login 時,它也會要求在上面的代碼中輸入標題,因為標題為空,這是我收到的錯誤:

JWT 令牌不以承載字符串開頭

登錄組件

<div class="container">
  <div>
    User Name : <input type="text" name="username" [(ngModel)]="username">
    Password : <input type="password" name="password" [(ngModel)]="password">
  </div>
  <button (click)=checkLogin() class="btn btn-success">
    Login
  </button>
</div>

安全方面的新手,請幫忙

我假設您的 angular 應用程序在調用它時根本不會顯示。 您不應該嘗試在同一台機器上的同一端口上運行兩個不同的服務,因為您的瀏覽器將無法區分哪些服務應該收到您的請求。

目前您正在向您的 API (URL:*/login) 發送一個 GET 請求,您可能尚未設置該請求。 因此,您將在錯誤消息中收到 404,但您希望將請求定向到您的 angular 應用程序以顯示您的應用程序(例如登錄掩碼)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM