如何使用jersey客户机对ws上的spring安全进行身份验证

zhte4eai  于 2021-06-30  发布在  Java
关注(0)|答案(1)|浏览(290)

我在jersey上的web服务带有以下安全配置(在spring上):

<?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"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
  http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.2.xsd">

    <!-- To allow public access by default and to set authentication mode to 
        basic login/password -->
    <security:global-method-security secured-annotations="enabled"/>

    <security:http>
        <security:http-basic/>
        <security:intercept-url pattern="/**" access="ROLE_DUMMY"/>
    </security:http>

    <!-- To delegate authorization to method calls rather than to urls -->
    <!-- (Thus, we don't need to set any url-interceptor in this conf) 
    <security:global-method-security
        pre-post-annotations="enabled" />-->

    <!-- To create user/password with roles -->
    <security:authentication-manager alias="authenticationManager">
        <security:authentication-provider>
            <security:user-service>
                <security:user authorities="ROLE_DUMMY" name="user1"
                    password="strongpassword1" />
            </security:user-service>
        </security:authentication-provider>
    </security:authentication-manager>
</beans>

现在我尝试为simulate the client创建一个java项目,因此我将client jersey框架用于:

ClientConfig config = new ClientConfig();

        Client client = ClientBuilder.newClient(config);

        WebTarget target = client.target(getBaseURI());

        System.out.println(target.path("general").path("getWeather").request().request().header("Authorization: ", "Basic " + "dXNlcjE6c3Ryb25ncGFzc3dvcmQx")
 .accept(MediaType.APPLICATION_JSON).get(Response.class)
.toString());

但是我有个错误:status=401,reason=unauthorized,如何设置授权?

wbgh16ku

wbgh16ku1#

我决定:

String authorization = "user1" + ":" + "strongpassword1";
String basic = new String(Base64.encodeBase64(authorization.getBytes(Charset.forName("US-ASCII"))));

System.out.println(target.path("generali").path("getMeteo").request().header("Authorization", "Basic " + basic).accept(MediaType.APPLICATION_JSON).get(String.class));

相关问题