简体   繁体   中英

Passing basic authentication details in spring security using http headers in java

I am implementing spring security in my restful web service. I am using http-basic authentication, right now when I try to access my service a windows security dialogue appears asking for user name and password, now I want to pass the user name and password via http header so that I don't need to enter the details exclusively in the security dialogue. My security config file looks like-

<beans:beans xmlns="http://www.springframework.org/schema/security"
    xmlns:beans="http://www.springframework.org/schema/beans" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    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.1.xsd">

    <http auto-config="true" create-session="stateless">
        <intercept-url pattern="/**" access="ROLE_USER" />
        <http-basic />
    </http>

    <authentication-manager>
      <authentication-provider>
       <!--  <user-service>
        <user name="yoman" password="123456" authorities="ROLE_USER" />
        </user-service> -->
        <jdbc-user-service data-source-ref="dataSource"

           users-by-username-query="
              select username,password, enabled 
              from users where username=?" 

           authorities-by-username-query="
              select u.username, ur.authority from users u, user_roles ur 
              where u.user_id = ur.user_id and u.username =?  " 

        />
      </authentication-provider>
    </authentication-manager>

</beans:beans> 

and I am trying to pass the username and password using authorization header like this-

HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.set("Authorization", "Basic "
        + "username:password");

But still everytime when I access the service its asking me for username and password.

What am I doing wrong and whats the correct way here. I will be really grateful for any help provided.

You can use RestTemplate with Apache Commons Http Client .Build a CommonsHttpClientFactory and inject it as constructor args to resttemplate and you are good to go.Here is some basic configuration to get you started.

context.xml

 <bean id="webServiceClient" class="com.webserviceclient.Client">
        <constructor-arg ref="restTemplate"/>
        <constructor-arg ref="credentials"/>
    </bean>

    <bean id="httpClientParams" class="org.apache.commons.httpclient.params.HttpClientParams">
        <property name="authenticationPreemptive" value="true"/>
        <property name="connectionManagerClass"
                  value="org.apache.commons.httpclient.MultiThreadedHttpConnectionManager"/>
    </bean>
    <bean id="httpClient" class="org.apache.commons.httpclient.HttpClient">
        <constructor-arg ref="httpClientParams"/>
    </bean>
    <bean id="credentials" class="org.apache.commons.httpclient.UsernamePasswordCredentials">
        <constructor-arg><value>${webservice.username}</value></constructor-arg>
        <constructor-arg><value>${webservice.password}</value></constructor-arg>
    </bean>
    <bean id="httpClientFactory" class="org.springframework.http.client.CommonsClientHttpRequestFactory">
        <constructor-arg ref="httpClient"/>
    </bean>

    <bean id="restTemplate" class="org.springframework.web.client.RestTemplate">
        <constructor-arg ref="httpClientFactory"/>

        <property name="messageConverters">
            <list>
                <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
                </bean>
            </list>
        </property>
    </bean>

    <bean id="jaxbMarshaller" class="org.springframework.oxm.jaxb.Jaxb2Marshaller">
        <property name="classesToBeBound">
            <list>
                <value>your classes</value>
            </list>
        </property>
    </bean>

Client.java

public class Client {

    private final RestTemplate restTemplate;
    private final Credentials credentials;


    public Client(RestTemplate restTemplate, Credentials credentials) {
        this.restTemplate = restTemplate;
        this.credentials = credentials;
        CommonsClientHttpRequestFactory factory = (CommonsClientHttpRequestFactory) restTemplate.getRequestFactory();
        HttpClient client = factory.getHttpClient();
        client.getState().setCredentials(AuthScope.ANY, this.credentials);
    }
    //consuming websevice
    public <yourObject> get(String url)
    {
      return restTemplate.getForObject(url, <yourObject>.class);
    }

}

Cheers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM