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

来自Javascript的Spring基本身份验证凭据

卞俊贤
2023-03-14

要求是实现一个登录表单,单击submit按钮时需要调用一个javascript,该javascript应该发布用户名/密码。

是否有方法从javascript向spring基本身份验证servlet传递凭据,使其验证请求。我们已经实现了AuthenticationProvider authenticate来执行验证。

import org.springframework.security.authentication.*;
import org.springframework.security.core.*;
import java.util.*;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.UriInfo;
import com.lifesciencemeta.ls.User;
import com.lifesciencemeta.ls.LifeScienceServiceMaster;
import com.lifesciencemeta.ls.LifeScienceConstants;

public class SpringBasicAuthentication implements AuthenticationProvider {
    public LifeScienceServiceMaster lifeScienceService;
    @Context
    UriInfo lsUri;
    public LifeScienceServiceMaster getLifeScienceService() {
        return lifeScienceService;
    }
    public void setLifeScienceService(LifeScienceServiceMaster lifeScienceService) {
        this.lifeScienceService = lifeScienceService;
    }
    @Override
    public Authentication authenticate(Authentication authentication)
            throws AuthenticationException {
        UsernamePasswordAuthenticationToken auth = (UsernamePasswordAuthenticationToken) authentication;
        String principal = (String) auth.getPrincipal();
        String credential = (String) auth.getCredentials();
        User u = lifeScienceService.authenticateUser(principal, credential);
        if (u == null)
            throw new BadCredentialsException(LifeScienceConstants.getMsg(“Auth Failed"));
        else {
            List<GrantedAuthority> grantedAuths = new ArrayList<GrantedAuthority>();
            String role = u.getRole().getName();
            if(role == null) {
                throw new BadCredentialsException(LifeScienceConstants.getMsg(“Auth Failed"));
            }
            grantedAuths.add(new SimpleGrantedAuthority(role));
            UsernamePasswordAuthenticationToken result = new UsernamePasswordAuthenticationToken(
                    principal, credential, grantedAuths);

            result.setDetails(u);
            return result;
        }

    }
    @Override
    public boolean supports(Class<?> authentication) {
        return authentication.equals(UsernamePasswordAuthenticationToken.class);

    }

}

http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd“id=”webapp_id“version=”2.5“>org.springframework.web.context.contextloaderlistener contextConfigLocation/web-inf/context.xml springSecurityFilterChain org.springframework.web.filter.delegatingfilterproxy springSecurityFilterChain/Jersey REST Service

  <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xmlns:security="http://www.springframework.org/schema/security"
           xmlns:context="http://www.springframework.org/schema/context"
           xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
               http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd
               http://www.springframework.org/schema/security
               http://www.springframework.org/schema/security/spring-security-3.1.xsd">
        <security:global-method-security secured-annotations="enabled" jsr250-annotations="enabled" pre-post-annotations="enabled" />
        <security:http>
              <security:intercept-url   pattern="/**"  access="ROLE_USER, ROLE_ADMIN"/>
             <security:http-basic />
        </security:http>
        <security:authentication-manager alias="authenticationManager">
            <security:authentication-provider ref="SpringBasicAuthentication" />
        </security:authentication-manager> 
        <bean id="SpringBasicAuthentication" 
            class="com.lifesciencemeta.ls.SpringBasicAuthentication" >
            <property name="lifeScienceService" ref="lsLifeScienceServiceImpl"/>
        </bean>
    </beans>

共有1个答案

邢小云
2023-03-14

您可以将spring security配置为使用基本身份验证,然后只需向任何受保护的资源发送请求,外加带有基本身份验证信息的授权头。

@SpringBootApplication
public class So44459836Application {

    public static void main(String[] args) {
        SpringApplication.run(So44459836Application.class, args);
    }

    @EnableWebSecurity
    public static class SecurityConfiguration extends WebSecurityConfigurerAdapter {
        @Override
        public void configure(WebSecurity web) throws Exception {
            web.ignoring().antMatchers("/public/**"); //for static resources
        }

        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http.formLogin().disable() //disable integrated login form 
                    .httpBasic().and() // we want http basic authentication
                    .authorizeRequests().anyRequest().authenticated(); // all requests are protected
        }
    }

    @RestController
    @RequestMapping("/api/me")
    public static class MeController {

        @GetMapping
        public String me(Principal principal) {
            return principal.getName(); // just return current username. 
        }
    }
}

示例表单

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>App</title>
</head>
<body>
<div>
    <section> <strong>Login</strong></section>

    <div>
        <label for="username">Username</label>
        <input type="text" id="username">
    </div>
    <div>
        <label for="password">Password</label>
        <input type="password" id="password">
    </div>

    <input type="button" onclick="login();" value="Authenticate">
</div>
</body>
<script type="text/javascript">
    'use strict';

    function login() {
        var username = document.getElementById('username').value;
        var password = document.getElementById('password').value;

        var  xhr = new XMLHttpRequest();
        xhr.open('GET', '/api/me', false, username, password);
        xhr.onload = function() {
            if (xhr.status === 200) {
                alert('User\'s name is ' + xhr.responseText);
            }
            else {
                alert('Request failed.  Returned status of ' + xhr.status);
            }
        };
        xhr.send();
    }
</script>
</html>

更新

<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_2_5.xsd" version="2.5">

    <display-name>Spring3 App</display-name>

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

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <servlet>
        <servlet-name>spring-web</servlet-name>
        <servlet-class>
            org.springframework.web.servlet.DispatcherServlet
        </servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>spring-web</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

</web-app>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <mvc:resources mapping="/public/**" location="/public/"/>
</beans>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:sec="http://www.springframework.org/schema/security"
       xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/security
        http://www.springframework.org/schema/security/spring-security.xsd">

    <context:component-scan base-package="com.stackoverflow.so44459836"/>
    <mvc:annotation-driven/>

    <sec:http auto-config="true">
        <sec:intercept-url pattern="/api/**" access="IS_AUTHENTICATED_FULLY" />
        <sec:http-basic/>
    </sec:http>

    <sec:authentication-manager>
        <sec:authentication-provider>
            <sec:user-service>
                <sec:user name="admin" password="admin" authorities="ROLE_ADMIN"/>
            </sec:user-service>
        </sec:authentication-provider>
    </sec:authentication-manager>
</beans>
 类似资料:
  • 我试图在一个反应式Spring Boot应用程序中配置一个Spring Security性,该应用程序具有一个Vuejs前端,在未经身份验证时将用户重定向到外部OpenID提供程序(用于身份验证)。在用户通过OpenID提供程序进行身份验证并重定向回应用程序(前端)后,将根据OpenID提供程序的响应创建用户名密码身份验证令牌(身份验证),并手动进行身份验证。 但是,在执行此操作时,应用程序似乎无

  • 我正在尝试使用OAuth2实现开发一个带有Spring Security性的rest api。但是如何删除基本身份验证呢。我只想向body发送用户名和密码,并在postman上获取令牌。 要删除基本身份验证,并从邮递员的get token中发送body标记中的用户名密码吗 我遇到了一些问题{"错误":"未经授权","error_description":"没有客户端身份验证。尝试添加适当的身份验证

  • 但我对spring-boot/java还是个新手...有谁能帮我把这条路走对吗? 多谢了。

  • 我正在将Monolith Java/Spring服务器重写为MicroService,同时向客户机公开相同的API接口,这样他们就不会注意到任何更改。 在Monolith服务器中,我们使用和。 第一部分是创建一个基于Java的API-Gateway,它将处理所有身份验证/授权作为通往Monolith服务器的隧道。 创建新的微服务(使用spring Initializer)后,我尝试将spring

  • 问题是当我尝试验证: 正文: 我总是有一个401错误状态,因为我的自定义入口点。在我看来,spring security并没有调用Authentication-Manager。我错过什么了吗?

  • http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.0.3.xsd“>