Spring Security : convert XML to Annotation - spring-mvc

I want to use the OpenID Connect client with Spring Java annotation.
Unfortunately, the sample Mitre ID Connect client is based on XML.
I managed to load XML by #ImportResource("classpath:servlet-context.xml")
but it would be much better to have pure Java annotation based solution.
I could not translate the following XML stuff into Spring Annotation:
<security:http auto-config="false" use-expressions="true"
disable-url-rewriting="true" entry-point-ref="authenticationEntryPoint"
pattern="/**">
<security:custom-filter before="PRE_AUTH_FILTER" ref="openIdConnectAuthenticationFilter" />
<security:logout />
</security:http>
<security:authentication-manager alias="authenticationManager">
<security:authentication-provider ref="openIdConnectAuthenticationProvider" />
</security:authentication-manager>
<bean id="authenticationEntryPoint" class="org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint">
<property name="loginFormUrl" value="http://localhost:10239/test" />
</bean>
<util:set id="namedAdmins" value-type="org.mitre.openid.connect.client.SubjectIssuerGrantedAuthority">
<bean class="org.mitre.openid.connect.client.SubjectIssuerGrantedAuthority">
<constructor-arg name="subject" value="XXX" />
<constructor-arg name="issuer" value="http://localhost:10239/test" />
</bean>
</util:set>

The bean xml tag is similar to the #bean annotation. See http://docs.spring.io/spring-javaconfig/docs/1.0.0.M4/reference/html/ch02s02.html
The util:set tag is similar to a method that returns a set of type org.mitre.openid.connect.client.SubjectIssuerGrantedAuthority. However this method has the #bean annotation as well.
For security related tags you can extend WebSecurityConfigurerAdapter
see https://www.mkyong.com/spring-security/spring-security-hello-world-annotation-example/

Related

How to bypass form login filter if pre-authentication was successful in spring?

Is it possible to bypass the form login filter if the pre-authentication filter successfully extracted user information from the request? The form login filter would be used as a fallback in case the incoming request was not pre-authenticated.
I am working on a spring mvc application that has a standard login page with two custom filters and an authentication provider defined as follows:
<security:http>
<security:custom-filter position="FORM_LOGIN_FILTER" ref="loginFilter"/>
<security:custom-filter after="FORM_LOGIN_FILTER" ref="postAuthFilter"/>
</security:http>
<bean id="loginAuthProvider" class="com.auth.LoginAuthProvider" />
<security:authentication-manager alias="authManager">
<security:authentication-provider ref="loginAuthProvider" />
</security:authentication-manager>
I added a third filter and another provider to handle pre-authenticated requests:
<bean id="preAuthFilter" class="com.auth.PreAuthFilter" >
<property name="authenticationManager" ref="authManager" />
</bean>
<security:http>
<security:custom-filter position="PRE_AUTH_FILTER" ref="preAuthFilter"/>
<security:custom-filter position="FORM_LOGIN_FILTER" ref="loginFilter"/>
<security:custom-filter after="FORM_LOGIN_FILTER" ref="postAuthFilter"/>
</security:http>
<bean id="preAuthProvider" class="com.auth.PreAuthProvider" />
<bean id="loginAuthProvider" class="com.auth.LoginAuthProvider" />
<security:authentication-manager alias="authManager">
<security:authentication-provider ref="preAuthProvider" />
<security:authentication-provider ref="loginAuthProvider" />
</security:authentication-manager>
However, the login form filter is invoked even though the pre-authentication provider explicitly set the authenticated flag to true: auth.setAuthenticated(true);

How to send property to the class inside dwrController?

I'm using spring mvc and dwr, I already made some tests and my configuration works, but now that I'm trying to access the database from the script I get a NullPointerException on this line:
List<Citas> citas = citasManager.select();
Obviously that means that the instance of "citasManager" is not being sent to the script but the property is defined on the bean, so I don't know the correct way I should define my bean so that the class "People" gets the instance.
My bean is defined as follows:
<bean id="dwr" class="dwr.People" scope="session">
<dwr:remote javascript="People">
<dwr:include method="createCrowd" />
<dwr:include method="getMatchingFromLargeCrowd" />
</dwr:remote>
<property name="citasManager" ref="citasManager" />
</bean>
I didn't know I was supossed to declare the setter method too. Even to everywhere else spring manages them on it's own.
<bean id="dwr" class="dwr.People" scope="session">
<dwr:remote javascript="People">
<dwr:include method="createCrowd" />
<dwr:include method="getMatchingFromLargeCrowd" />
<dwr:include method="setCitasManager" />
</dwr:remote>
<property name="citasManager" ref="citasManager" />
</bean>

How to change spring security oauth2 default token endpoint?

We have spring security oauth2 based application. Every thing is working fine. But i am failed to change default token endpoint from "/oauth/token" to "/external/oauth/token".
My spring-servlet.xml
<http pattern="/external/oauth/token" create-session="stateless"
authentication-manager-ref="clientAuthenticationManager"
use-expressions="true" xmlns="http://www.springframework.org/schema/security">
<intercept-url pattern="/external/oauth/token" access="isFullyAuthenticated()" />
<anonymous enabled="false" />
<http-basic entry-point-ref="clientAuthenticationEntryPoint" />
<!-- include this only if you need to authenticate clients via request parameters -->
<custom-filter ref="clientCredentialsTokenEndpointFilter" after="BASIC_AUTH_FILTER" />
<access-denied-handler ref="oauthAccessDeniedHandler"/>
</http>
<oauth:authorization-server client-details-service-ref="clientDetails"
token-services-ref="tokenServices"
user-approval-handler-ref="userApprovalHandler" token-endpoint-url="/external/oauth/token">
<oauth:authorization-code />
<oauth:implicit />
<oauth:refresh-token />
<oauth:client-credentials />
<oauth:password />
</oauth:authorization-server>
But the result when i access this endpoint is
{
error: "unauthorized"
error_description: "An Authentication object was not found in the SecurityContext"
}
am i missing any thing ? Please suggest.
With the version 2.0.5.RELEASE or above of spring-security-oauth2
In one line in java based configuration, tested and works fine, somehow it's overriding the RequestMapping value of the TokenEndpoint class.
#Configuration
#EnableAuthorizationServer
protected static class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {
#Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints
.pathMapping("/oauth/token", "<your custom endpoint>")
}
}
Just struggled with this for a few days, but have it working now on latest Spring Oauth2 1.0.5.RELEASE. I'm not 100% sure my solution is the classiest (Step 4 in particular), but it works and I'm able to move forward.
In my case, I wanted to remove the /oauth prefix from the urls to end up with just /token and /authorize. The solution for me was mostly xml config, with two hacks to override endpoint request mappings.
1 - In app context xml, add authorization-endpoint-url and token-endpoint-url attribs to your <oauth:authorization-server> element.
Mine:
<oauth:authorization-server client-details-service-ref="clientDetailsService" token-services-ref="tokenServices" user-approval-handler-ref="userApprovalHandler" authorization-endpoint-url="/authorize" token-endpoint-url="/token">
2 - In app context xml, adjust the security endpoints accordingly. There should be two, which respectively manage security on the token and auth urls. Need to update the pattern prop on <http> and <intercept-url> tags.
Mine:
<http pattern="/token/**" create-session="stateless" authentication-manager-ref="clientAuthenticationManager" xmlns="http://www.springframework.org/schema/security">
<intercept-url pattern="/token/**" access="IS_AUTHENTICATED_FULLY" />
...
<http pattern="/authorize/**" access-denied-page="/login.jsp?authorization_error=true" disable-url-rewriting="true" xmlns="http://www.springframework.org/schema/security">
<intercept-url pattern="/authorize/**" access="IS_AUTHENTICATED_FULLY" />
3 - (If you chose to employ the optional clientCreds filter.) In app context xml, you should already have wired-in the clientCredentialsTokenEndpointFilter bean as a <custom-filter> within yourelement. So, within the filter's bean, add afilterProcessesUrl` property.
Mine:
<bean id="clientCredentialsTokenEndpointFilter" class="org.springframework.security.oauth2.provider.client.ClientCredentialsTokenEndpointFilter">
<property name="authenticationManager" ref="clientAuthenticationManager" />
<property name="filterProcessesUrl" value="/token" />
</bean>
4 - The last step is to override the request mapping urls of the actual internal endpoint controllers. The spring oauth2 lib comes with two classes: AuthorizationEndpoint and TokenEndpoint. Each use #RequestMapping type annotations to bind the url (as we all do for our projects' app controllers). For me, it was a hair-pulling effort to attempt to override the value of the request mappings in any way other than to (sadly) recreate the spring class package in my src folder, copy the AuthorizationEndpoint and TokenEndpoint classes verbatim into said folder, and edit the inline #RequestMapping annotation values.
Anyway, that does the trick. Would love to hear of a more graceful way to override the endpoint controller request mapping values.
Thanks.
Final, working app context:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:sec="http://www.springframework.org/schema/security" xmlns:oauth="http://www.springframework.org/schema/security/oauth2"
xsi:schemaLocation="
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.2.xsd
http://www.springframework.org/schema/security/oauth2 http://www.springframework.org/schema/security/spring-security-oauth2.xsd
"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
>
<!-- Declare OAuth2 services white-list. (This is the top of the config.) -->
<oauth:authorization-server client-details-service-ref="clientDetailsService" token-services-ref="tokenServices" user-approval-handler-ref="userApprovalHandler" authorization-endpoint-url="/authorize" token-endpoint-url="/token">
<oauth:authorization-code />
<oauth:implicit />
<oauth:refresh-token />
<oauth:client-credentials />
<!-- <oauth:password /> -->
</oauth:authorization-server>
<bean id="userApprovalHandler" class="org.springframework.security.oauth2.provider.approval.TokenServicesUserApprovalHandler">
<!-- This bean bridges client auth service and user tokens... kind of an out of place requirement. -->
<property name="tokenServices" ref="tokenServices" />
</bean>
<!-- This starts the far back-end config for client token management. -->
<sec:authentication-manager id="clientAuthenticationManager">
<sec:authentication-provider user-service-ref="clientDetailsUserService" />
</sec:authentication-manager>
<bean id="clientDetailsUserService" class="org.springframework.security.oauth2.provider.client.ClientDetailsUserDetailsService">
<constructor-arg ref="clientDetailsService" />
</bean>
<bean id="clientDetailsService" class="com.mycompany.oauth.spring.security.oauth2.IntegratedOauth2ClientDetailsService">
<!-- This bean is what wires OAuth2 into the persistence stack for client details stored in the oauth_client table. -->
</bean>
<!-- OAuth is layered on to spring security which is centered around users which requires a user auth manager. -->
<authentication-manager alias="authenticationManager" xmlns="http://www.springframework.org/schema/security">
<authentication-provider ref="daoAuthenticationProvider" />
</authentication-manager>
<bean id="daoAuthenticationProvider" class="org.springframework.security.authentication.dao.DaoAuthenticationProvider">
<property name="userDetailsService" ref="userDetailsService" />
</bean>
<bean id="tokenServices" class="org.springframework.security.oauth2.provider.token.DefaultTokenServices">
<property name="tokenStore" ref="tokenStore" />
<property name="supportRefreshToken" value="true" />
<property name="clientDetailsService" ref="clientDetailsService" />
</bean>
<bean id="tokenStore" class="com.mycompany.oauth.spring.security.oauth2.IntegratedOAuth2TokenStore">
<!-- This bean is what wires OAuth2 tokens into my company's application stack. -->
<constructor-arg ref="dataSource" />
</bean>
<!-- **************************************************************************************** -->
<!-- Finally, sew OAuth into spring security with some http tags... -->
<!-- **************************************************************************************** -->
<!-- The OAuth2 endpoint for direct token requests (i.e. for client_credentials flow). -->
<http pattern="/token/**" create-session="stateless" authentication-manager-ref="clientAuthenticationManager" xmlns="http://www.springframework.org/schema/security">
<intercept-url pattern="/token/**" access="IS_AUTHENTICATED_FULLY" />
<anonymous enabled="false" />
<http-basic entry-point-ref="clientAuthenticationEntryPoint" />
<custom-filter ref="clientCredentialsTokenEndpointFilter" before="BASIC_AUTH_FILTER" />
<access-denied-handler ref="oauthAccessDeniedHandler" />
</http>
<bean id="clientCredentialsTokenEndpointFilter" class="org.springframework.security.oauth2.provider.client.ClientCredentialsTokenEndpointFilter">
<property name="authenticationManager" ref="clientAuthenticationManager" />
<property name="filterProcessesUrl" value="/token" />
</bean>
<bean id="clientAuthenticationEntryPoint" class="org.springframework.security.oauth2.provider.error.OAuth2AuthenticationEntryPoint">
<property name="realmName" value="myrealm" />
</bean>
<bean id="oauthAccessDeniedHandler" class="org.springframework.security.oauth2.provider.error.OAuth2AccessDeniedHandler" />
<!-- The OAuth2 endpoint for user-approved authorization (i.e. for "authorization" flow involving user login/approve). -->
<http pattern="/authorize/**" access-denied-page="/login.jsp?authorization_error=true" disable-url-rewriting="true" xmlns="http://www.springframework.org/schema/security">
<intercept-url pattern="/authorize/**" access="IS_AUTHENTICATED_FULLY" />
<form-login authentication-failure-url="/login.jsp?authentication_error=true" default-target-url="http://www.mycompany.com/" login-page="/login.jsp" login-processing-url="/login.do" />
<http-basic />
<anonymous />
</http>
</beans>
For customize the token end point URL, do the following steps.
1) Write your own class that extends ClientCredentialsTokenEndpointFilter class & call ClientCredentialsTokenEndpointFilter class constructor with "/external/oauth/token" value.
super("/external/oauth/token");
2) Plug your new customize filter in security configuration.
Replace
<custom-filter ref="clientCredentialsTokenEndpointFilter" after="BASIC_AUTH_FILTER" />
with
<custom-filter ref="your customize filter" after="BASIC_AUTH_FILTER" />
3) Create your own class for new mapping (/external/oauth/token) & extend tokenendpoint.
4) Change http & intercept-url element's pattern attribute value to "/external/oauth/token"
You are making this harder than what it should be, it's actually very simple !
(Notice I'm using "oauth2:" instead of "oauth:" as the XML tag)
Go to your security-context.xml
Find "oauth2:authorization-server" in the above file.
<oauth2:authorization-server
client-details-service-ref="someService"
request-validator-ref="someScopeRequestValidator"
token-services-ref="someTokenServices" >
Just add token-endpoint-url="/oauth/whatever_you_like"
<oauth2:authorization-server
client-details-service-ref="someService"
request-validator-ref="someScopeRequestValidator"
token-services-ref="someTokenServices"
**token-endpoint-url="/oauth/whatever_you_like"** >

How to config basing condition in Spring IOC?

How can I config IOC basing condition,like following:
<bean id="beanid" class="com...Class1" >
<if var='xxx'>
<property name="formView"
value="RegistrationApprovalForm" />
<else if var ='yyy'>
<property name="formView"
value="RegistrationApprovalForm1" />
</bean>
so I can put var in properties files,this will make configration easy.
Here is the code.
${ServiceMgmt.showEnabler}
</bean>
I want to redirect to the view based on configuration as below.
else
Is this possible with spring configuration??

Trouble with object injection in Spring.Net

I have a issue with my Spring.Net configuration where its not injecting an object. I have a CommService to which an object named GeneralEmail is injected to. Here is the configuration:
<!-- GeneralMail Object -->
<object id="GeneralMailObject" type="CommUtil.Email.GeneralEmail, CommUtil">
<constructor-arg name="host" value="xxxxx.com"/>
<constructor-arg name="port" value="25"/>
<constructor-arg name="user" value="xxxx#xxxxx.com"/>
<constructor-arg name="password" value="xxxxx"/>
<constructor-arg name="template" value="xxxxx"/>
</object>
<!-- Communication Service -->
<object id="CommServiceObject" type="TApp.Code.Services.CommService, TApp">
<property name="emailService" ref="GeneralMailObject" />
</object>
The communication service object is again injected to many other aspx pages & service. In one scenario, I need to call the commnucation service from an static WebMethod. I try doing:
CommService cso = new CommService();
But when i try to get the emailService object, its null! why didn't the spring inject the GeneralMail object into my cso object? What am I doing wrong and how do I access the object from spring container.
Thanks in advance for the suggestions and solutions.
Reagrds,
Abdel Olakara
IApplicationContext ctx = ContextRegistry.GetContext();
CommService cso= (CommService)ctx.GetObject("CommServiceObject");

Resources