如何使用Jersey Client对WS上的Spring Security进行身份验证

时间:2015-01-15 08:44:12

标签: java spring web-services rest

我在泽西岛上有我的网络服务这个conf用于安全性(在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>

现在我尝试创建一个用于模拟客户端的java项目,所以我使用客户端泽西框架:

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 =未经授权,如何设置授权?

1 个答案:

答案 0 :(得分:0)

我决心:

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