当前位置: 首页 > 知识库问答 >
问题:

SpringBoot安全性:在Angular 8中显示登录页面时出现问题

芮瑾瑜
2023-03-14

我正在为我的项目实现登录功能。在前端,我使用角度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请求

Web安全配置

 @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/登录时,我面对的还是浏览器

应用程序没有针对/错误的显式映射,因此您将其视为回退。

Wed Feb26 14:42:50IST 2020出现意外错误(type=Not查找,status=404)。没有可用的消息

在后端,我面临

2020-02-26 14:30:44.045 WARN 5184---[nio-8090-exec-1]组织。自由职业者。utils。JwtRequestFilter:JWT令牌不是以承载字符串2020-02-26 14:42:49.945 WARN 5184-[nio-8090-exec-3]org开头。自由职业者。utils。JwtRequestFilter:JWT令牌不是以承载字符串2020-02-26 14:42:51.287 WARN 5184-[nio-8090-exec-4]org开头。自由职业者。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令牌不以不记名字符串开头

LoginComponent

<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>

不熟悉安全知识,请帮忙

共有1个答案

鞠建安
2023-03-14

我假设您的角度应用程序在调用它时根本不会显示。您不应该尝试在同一台机器的同一端口上运行两个不同的服务,因为您的浏览器将无法区分您的请求应该获得哪些服务。

当前,您正在向您的API(URL:*/login)发送GET请求,您可能尚未设置该请求。因此,您将在错误消息中看到404,但您希望请求被定向到您的angular应用程序以显示您的应用程序(例如登录掩码)。

 类似资料:
  • 我在Spring MVC中显示jsp页面时遇到了问题。这是一个带有Gradle和IntelliJ CE的基本hello world Spring MVC: 我得到以下错误页面: 这是我的身材。格拉德尔: 视图解析器文件: 控制器页面: jsp页面位置: application.properties文件内容: 使用默认模板引擎,页面显示正确,但使用jsp,它无法工作 日志错误: https://ha

  • 嗨,我正在尝试用我已经开始的Java15为静态编程语言Spring Boot项目添加安全性。我想使用KeyCloak作为验证服务器。 我还没有前端(REACT应用程序),我首先构建REST API。 我的问题是,当我尝试点击受保护的endpoint而不是使用Keycloak登录页面时,我想会弹出Spring Security登录页面,因为它显示无效凭据,并且外观是基本形式,而不是Keycloak用

  • 谁是代码,需要放在哪里,以显示会话用户名为登录用户的会话fname和lname。 这是我的登录页面: 这是我的会员页面: 当使用此代码“print_r($_SESSION)”时,仅打印用户名和成员id。我厌倦了使用“$_SESSION['Fname']=$_POST['Fname'];”

  • 通过设置安全码,从而达到隐藏登录页的效果,保证页面的私有性。 /app/Application/Admin/Conf/config.php return array( 'LOGIN_MAX_FAILD' => 5, 'BAN_LOGIN_TIME' => 30, //登录失败5次之后需等待30分钟才可再次登录 'ADMIN_PANEL_SECURITY_CODE' => '

  • 我已将Websphere Liberty服务器配置为支持IBM知识中心中所述的管理中心。 我在Eclipse Neon环境(即localhost)的Windows 10上运行WASLiberty版本17.0.0.1。我从Chrome(版本61)连接URL(http://localhost:9080/adminCenter)。 它会显示一个登录页面(外观不好看,但可用) 我输入我的凭据并单击“提交”