w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Spring MVC + Spring Security login with a rest web service
you can define a custom pre-auth filter by extending AbstractPreAuthenticatedProcessingFilter. In your implementation of getPreAuthenticatedPrincipal() method you can check if cookie exists and if it exists return cookie name is principal and cookie value in credentials. Use PreAuthenticatedAuthenticationProvider and provide your custom preAuthenticatedUserDetailsService to check if cookie is vali, if its valid also fetch granted authorities else throw AuthenticationException like BadCredentialsException For authenticating user using username/password, add a form-login filter, basic-filter or a custom filter with custom authentication provider (or custom userdetailsService) to validate user/password In case cookie exists, pre auth filter will set authenticated user in sprin

Categories : Spring

Grails: create rest api with plugin jaxrs and protect resource with spring security oauth?
i believe you should use the annotation @Secured provided by spring security in your rest controllers or methods import grails.plugins.springsecurity.Secured @Secured(['YOUR_ROLE'])

Categories : Grails

Spring Security UI plugin for Grails creates neither spring-security-ui.css nor i18n files
Try extracting the files from the directory you need, from the version you need https://github.com/grails-plugins/grails-spring-security-ui/tree/master/grails-app/assets/stylesheets https://github.com/grails-plugins/grails-spring-security-ui/tree/master/grails-app/i18n

Categories : Grails

Grails Spring Security plugin - "Cannot invoke isLoggedIn() on null object" error in grails-2.3.0.RC1
Obviously, this problem is related to an issue with grails-2.3.0.RC1 not injecting service bean for plugins correctly. I was able to fix my problem by adding this to grails-app/conf/resources.groovy beans = { springConfig.addAlias "springSecurityService", "springSecurityCoreSpringSecurityService" } This makes grails to inject the service first before anything. If you have similar problems using grails-2.3.0RC1, you can add an alias to the resources.groovy file to fix this error. For example: beans={ springConfig.addAlias "serviceName","pluginNameServiceName" } You can see the jira that was opened for this problem here http://jira.grails.org/browse/GRAILS-10301 Hope this helps anyone with similar issues.

Categories : Java

Spring security override specific message : Your login attempt was not successful, try again. - not found under org.springframework.security
Actually it is easy resolvable by custom login form. Since it won't display any of sf error messages we can pass error param back after processing. Consequently simply check for this param and add whatever text message you like. authentication-failure-url="/login?error=true" then in our new login page simply add something like: <c:if test="${error}"> <s:message code="AbstractUserDetailsAuthenticationProvider.badCredentials"/></c:if> where you can use any message code from your resource bundle.

Categories : Spring

Spring security 3.2.0 > deprecated
I'm not sure if this answer can help you. However, the warning message generated by IDE is not a big problem because you did not use the deprecated method. I'm using spring security too and I also can see the same warning message but the service is working perfectly. I'm sorry if the answer is not you wanted.

Categories : Spring

Handling failed login notifications with Spring Security 3 login handlers
An alternative way to recieve notifications about authentication events is to listen for ApplicationEvents broadcasted by Spring Security, namely, AuthenticationSuccessEvent and AbstractAuthenticationFailureEvent.

Categories : Spring

Using Spring Security in Grails with CAS and LDAP
I've shared (GitHub) a sample app that integrates Grails (2.2.0) + Spring Security Plugin + CAS + LDAP. My work is based on this link: http://dominikschuermann.de/index.php/2010/11/using-grails-with-cas-and-ldap/, but unfortunately the link is not active. https://github.com/luizcantoni/TestCAS-LDAP-Grails This App authenticates using CAS. After authenticated, CAS redirect to Grails that populates (through ldap) the User with some Active Directory information (email and name). This is the file that populates the user with some AD information: https://github.com/luizcantoni/TestCAS-LDAP-Grails/blob/master/src/groovy/example/PrepopulateUserDetailsService.groovy Check the resources.groovy: https://github.com/luizcantoni/TestCAS-LDAP-Grails/blob/master/grails-app/conf/spring/resources.groo

Categories : Grails

How to get current_user by using Spring Security Grails plugin in GSP
Try tags provided by springSecurity plugin, something like: <sec:isLoggedIn> <g:link controller="post" action="edit" id="${post.id}"> Edit this post </g:link> </sec:isLoggedIn> Actually you are trying to inject a service on your GSP page, you can do it with some import statement on the page, but I would say it will not be good programming practice, I think you should send current logged In user's instance from the controller to the GSP page, and then perform a check on it: let say you have the controller method: def showPostPage(){ Person currentLoggedInUser = springSecurityService.getCurrentUser(); [currentLoggedInUser:currentLoggedInUser] } and on your GSP page: <g:if test="${post.author == currentLoggedInUser }"> <g:l

Categories : Grails

Grails - different passwords for same salt in Spring Security
bcrypt generates a uniq salt each time, and includes it into result hash. Because of it springSecurityService.encodePasswod just ignores second argument, and reflectionSaltSourceProperty option as well (see sources). So, each time you'll get different hash for same input data. You can use BCrypt class to validate password, like: if (BCrypt.checkpw(candidate_password, stored_hash)) System.out.println("It matches"); else System.out.println("It does not match"); See docs for BCrypt: http://static.springsource.org/autorepo/docs/spring-security/3.1.x/apidocs/org/springframework/security/crypto/bcrypt/BCrypt.html Btw, as you're using Spring Security, it's already implemented in framework, so you can use passwordEncoder bean: def passwrodEncoder ... passwordEncoder.isPasswordValid(

Categories : Grails

Spring Security in Grails providing authorization
You can use your Role class not only for generic roles (Admin,User, etc.), but for application specific ones as well. Simply allow the user to create a Role for a resource and then allow their invitees to be granted that role. Spring Security comes with a handy ifAnyGranted() method, which accepts a comma-delimited String of role names. At a resource entry-point simply ensure that a particular role is granted: class Conversation{ Role role } class ConversationController{ def enterConversation(){ // obtain conversation instance if(!SpringSecurityUtils.ifAnyGranted(conversationInstance.role.authority){response.sendError(401)} } }

Categories : Grails

grails spring security acl query exception
I believe the default UserDetailsService looks up a user based on username, so in addition to what you've configured, you'll also need to create a custom UserDetailsService and implement the loadUserByUsername method. Here's a quick example: class CustomUserDetailsService implements GrailsUserDetailsService { UserDetails loadUserByUsername(String username, boolean loadRoles) throws UsernameNotFoundException { return loadUserByUsername(username) } UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { User.withTransaction { status -> User user = User.findByEmail(username) if (!user) { throw new UsernameNotFoundException('User not found', username) } def authorities = user.authorities.collect { new Grant

Categories : Authentication

Trouble logging out from a Grails application using Spring Security (CAS)
Have you tried call session.invalidate() direct in the controller index method? class LogoutController { def index = { println "IN LOGOUT CONTROLLER TRYING TO LOGOUT" session.invalidate() redirect uri: SpringSecurityUtils.securityConfig.logout.filterProcessesUrl } } Cheers

Categories : Grails

Adding Spring Security dependency to Grails plugin
The plugins block is correct. If it's not working after installing from a zip, you might have some cruft left over from before. To keep things in one place, I like to remove grails.project.class.dir = "target/classes" grails.project.test.class.dir = "target/test-classes" grails.project.test.reports.dir = "target/test-reports" and replace them with grails.project.work.dir = 'target' so everything is under the target folder. When things get weird, run rm -rf target to force a full re-resolve and rebuild. Then, rather than using inline plugins (which aren't great about transitive deps because we read that info from POM files now and that's not available unless you package the plugin properly) or zips, use the release plugin's maven-install script. Add this to the plugins section (re

Categories : Grails

grails spring security - implementing screen lock
If you are saving encoded passwords to DB then You need to do something like this def userInstance = ... //get user instance if (springSecurityService.encodePassword(params.pass) != userInstance.password) { ... }

Categories : Grails

Grails: disable Spring Security Core on certain paths
You can implement a simple non-authentication filter:: class NonAuthenticationFilter extends GenericFilterBean { void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { chain.doFilter(request, response); } } Define it in resources.groovy: beans = { nonAuthFilter(NonAuthenticationFilter) } And configure your url pattern: grails.plugins.springsecurity.filterChain.chainMap = [ '/api/**': 'nonAuthFilter', '/**': 'JOINED_FILTERS', ] grails.plugins.springsecurity.interceptUrlMap = [ '/api/**': ['IS_AUTHENTICATED_ANONYMOUSLY'] ]

Categories : Spring

Grails Spring Security & LDAP Auth Failure
Try these settings: grails.plugins.springsecurity.ldap.authorities.groupSearchBase ='DC=example,dc=org' grails.plugins.springsecurity.ldap.authorities.groupSearchFilter = 'member={0}'

Categories : Spring

Change AccessDecisionManager to UnanimousBased in Grails Spring Security Plugin
Based on Burt Beckwith's "Hacking the Grails Spring Security Plugin" [http://www.slideshare.net/gr8conf/hacking-the-grails-spring-security-plugins], it should be possible to simply provide a different implementation of the accessDecisionManager bean. Something like this: accessDecisionManager(org.springframework.security.access.vote.UnanimousBased) in resources.groovy When I tried this, I had trouble with the constructor syntax in the bean definition. The access decision manager wants a list of voters in the constructor and I couldn't quote figure out how to get my voters defined in config.groovy as parameters to the constructor. I was about to derive my own decision manager (with parameterless constructor) from UnanimousBased when I stumbled upon the source code for AuthenticatedVetoab

Categories : Grails

Grails Database migration problems with Spring Security password
So in grails-app/conf/spring/resources.groovy you can specify the password encoder bean beans = { passwordEncoder(YourClassHere) } The class must implement PasswordEncoder. In your class you can do whatever you did previously to encrypt the passwords.

Categories : Grails

Grails Spring Security Core Plugin redirect issue
I might be wrong, but I don't think you can do what you want using ['IS_AUTHENTICATED_ANONYMOUSLY'], it won't restrict logged in user since per documentation The token accepts any authentication, even anonymous. Why not just put something like //in user controller def create() { if(springSecurityService.currentUser) { //let them know they're already logged in flash.message = message(code: 'your.....message') redirect(action: "list") } //else take them to create form ... }

Categories : Grails

Grails Spring Security interceptUrlMap: how to restrict access of index.gsp
grails.plugins.springsecurity.interceptUrlMap = [ '/testcontroller/**': ["isAuthenticated()"], '/*': ["isAuthenticated()"] ] This is stricter. Authenticates non-anonymous user from anonymous user at the root context. Should this work?

Categories : Grails

How to set custom time out for remember me cookie in grails spring security?
Override the method calculateLoginLifetime, by default this will return the value as set in the configuration (it calls getTokenValiditySeconds(). By overriding this you can determine (based on the request) if the normal timeout should be passed or a custom one. protected int calculateLoginLifetime(HttpServletRequest request, Authentication authentication) { if (request.getRemoteAddr().startsWith("subdomain") { return 15; // Or whatever you want, you could also make it configurable. } return getTokenValiditySeconds(); }

Categories : Grails

grails and spring security acl: show only some instances of a domain class
If I understand you right you need to define belongsTo. This will create mapping in database from Patient to User. Edit: to get current logged in user use class SomeController { def authenticateService def list = { def user = authenticateService.principal() def username = user?.getUsername() ..... ..... } } To map to user change logic in controller or use events to create mapping Edit: edit create action: class PatientController { def authenticateService ... def create() { def patientInstance = new Patient(params) patientInstance.user = authenticateService.principal() ... [patientInstance: patientInstance] } ... }

Categories : Grails

Spring security redirection after login
To force spring-security to go to /pages/index.xhtml, you can use property always-use-default-target as this : <form-login login-page='/pages/login.xhtml' default-target-url="/pages/index.xhtml" always-use-default-target="true" authentication-failure-url="/pages/login.xhtml"/> Otherwise, the login page should be shown automatically by spring security when the user calls a secured resource, and once login done, continue to the secured resource it was originally asked for. In your case, some confusion seems to come from the fact that you want spring security to handle the login, and you try to handle it yourself with a jsf actionListener and navigation rules. putting "<form-login [...]" in the configuration essentially t

Categories : Spring

Spring Security ajax login interpreted as regular login request (not AJAX)
I fixed the problem by adding the following line to the action that render the view that contains the ajax form: session.SPRING_SECURITY_SAVED_REQUEST_KEY = null You can find more details on why this solves the problem on the following link: Spring Security Core authAjax, How do I ignore the Referer

Categories : Jquery

Spring security jsf not redirecting after successsfull login
In Spring Security 3.x, you can achieve it using an authentication handler, which allows you writing your custom servlet code to manage a successful authentication. I know you are using Spring Security 2 but if upgrading is an option you can consider it. I firstly declare the login form for the access and make it available for every user. Appart from that, I leave the rest of the urls restricted: <http use-expressions="true"> <intercept-url pattern="/login**" access="permitAll()" /> <intercept-url pattern="/**" access="isAuthenticated()" /> <form-login login-page="/login" default-target-url="/home" always-use-default-target="false" authentication-success-handler-ref="authenticationSuccessHandler" authentication-failure-handler-ref

Categories : JSF

Spring security *always* redirects to login form
Is it working if you connect to remote jetty directly using port 8080? If it is, the problem is probably related to nginx. When Spring Security auth succeeds, it should be able to set a cookie on browser via Set-Cookie header in the response. Maybe nginx has trouble with that. You could debug using the traffic with Chrome, press F12 and open Network tab. Go to login page and try to login. You should be able to see cookie JSESSIONID in the Cookies tab if it succeeds.

Categories : Maven

Login Logout use case in Spring security
The UsernamePasswordAuthenticationFilter intercepts requets sent to /j_spring_security_check (by default), so most probably you only need to remove the .htm ending from the action URL in login.jsp: <form name='f' action="<c:url value='j_spring_security_check'/>" method="POST"> Oh well, it seems some stuff is missing from web.xml as well. You will need to set up the security filter chain: <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>

Categories : Java

Spring security auto login after registeration
I had been faced with the similar problem. In legacy code the password was hashed by hand. The better choice is to store object of User class (may be it is a plain form binding) with the plain password and clear it later. Clearing credencials is the responsibility of spring-security too (interface org.springframework.security.core.CredentialsContainer). If it isn't possible remove tag of encoder or use the plain text encoder <password-encoder hash="plaintext"/>.

Categories : Spring

Spring security: change locale on login
Rather than making a custom AuthenticationSuccessHandler set the locale, why not implement an custom LocaleResolver that resolves the locale from the UserDetails object (using SecurityContextHolder.getContext().getAuthentication() to get the authentication object)?

Categories : Spring

Multiply login forms Spring Security GWT
You can have as many login forms as you want. Just place it on every JSP page you want: <form name='f' action="<c:url value='j_spring_security_check' />" method='POST'> User: <input type='text' name='j_username' /> Password: <input type='password' name='j_password' /> <input name="submit" type="submit" value="submit" /> </form> It does not metter how many login forms do you have. They all will be submitted to the same j_spring_security_check URL and so they all will be processed by the same spring security filter. The same auhentication manager will be used. You can have multiple authentication managers.

Categories : Java

Spring security login controller methods
Personally I use this way to set Spring-Security context values: import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; //.... //In your login method: List<Authority> auths = new ArrayList<Authority>(); auths.add(new Authority("ROLE_USER")); //Role here, like "admin" Authentication authentication = new UsernamePasswordAuthenticationToken(token, null, auths); SecurityContextHolder.getContext().setAuthentication(authentication); The Authority class is as follow: import org.springframework.security.core.GrantedAuthority; public class Authority implements GrantedAuthority{ private static final long serialVersion

Categories : Spring

Integrate GWT with Spring Security with custom login page
I have found another solutions for GWT and Spring Security integration: http://www.site.lalitbhatt.com/spring-security-gwt-integration this article make a login.html rather that jsp. Very easy to understand and implement. Everthing works fine now. Updated: The link moved to http://tech.lalitbhatt.net/2014/08/spring-security-gwt-integration.html

Categories : Gwt

Spring Security + LDAP: session is cleared right after Login
Solved. The problem was related to the redirection of the page after the login. I used the following line of code: FacesContext.getCurrentInstance().getExternalContext().redirect("inicio.xhtml"); I got the idea after reading this post The LoginBean.java looks as follows: public String doLogin() throws IOException, ServletException { try { ExternalContext context = FacesContext.getCurrentInstance().getExternalContext(); RequestDispatcher dispatcher = ((ServletRequest)context.getRequest()).getRequestDispatcher("/j_spring_security_check"); dispatcher.forward((ServletRequest)context.getRequest(), (ServletResponse)context.getResponse()); FacesContext.getCurrentInstance().responseComplete(); FacesContext.getCurre

Categories : JSF

Spring Security need to redirect to Login Page on BadCredentialsException
Take a look here: http://www.codemarvels.com/2010/12/spring-security-3-how-to-display-login-errors/ To sum up, it says that you should capture in a controller the different mappings used in authenticationFailureHandler. Then you can redirect to any jsp and use the messages you need.

Categories : Spring

Spring Security: redirect to a URL with path variable after successful login
You can save the account ID into the spring security session object and retrieve the object when is called the quickview url. to redirect to the url add into the bean customAuthenticationSuccessHandler the following property <property name="authenticationSuccessHandler" ref="successHandler" /> and create the successHandler bean: <bean id="successHandler" class="org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler"> <property name="defaultTargetUrl" value="/account/quickview" /> <property name="alwaysUseDefaultTargetUrl" value="true" /> </bean> regards

Categories : Spring

Spring 3.2 Security - Login with non-unique username and additional info
Your question is not all clear to me. Do you have a unique login for multiple stores? Then you don't need to give the store to your UserDetailsService implementation. I would simply load the user information using its username and if the users are not authorized for all the stores, you could use the GrantedAuthority to define where the users is authorized, e.g. ROLE_STORE_ID1, ROLE_STORE_ID2, etc. If you have multiple stores where users are not shared, then you could simply create a configurable custom implementation of UserDetailsService, instantiate one per store and uses the correct instance depending on the store the user is accessing. I hope this will help.

Categories : Java

Sencha Touch 2 & Spring Security cross-domain login
You can use requestcomplete & beforerequest events to read response headers and to write request headers respectively. Here is sample code : Ext.Ajax.on('requestcomplete', function(conn, response, options, eOpts){ var respObj = Ext.JSON.decode(response.responseText); Helper.setSessionId(options.headers['JSESSIONID']); }, this); Ext.Ajax.on('beforerequest', function(conn, options, eOptions){ options.headers['JSESSIONID'] = Helper.getSessionId(); }, this);

Categories : Spring

How to divide secured and unsecured area using Spring Security login
If everything is in a single war and you don't want to modify the controllers simply add another DispatcherServlet to your web.xml. <servlet> <servlet-name>member</servlet-name> // Other properties </servlet> <servlet-mapping> <servlet-name>member</servlet-name> <url-pattern>/member/*</url-pattern> </servlet-mapping> This servlet contains/loads all the dynamic controllers, where as your current servlet will serve and handle all the static content. You might need to restruce your configuration a little. When using multiple DispatcherServlet instances and when Spring Security is mapped to only one of them (in this case /member/*), remember to configure the <form-login .. /> element properly. You need t

Categories : Spring

How to get the plain user credentials while login with spring security before encrypting them?
You could use an AuthenticationSuccessHandler and implement your logic in its onAuthenticationSuccess(request, response, authentication) method, where you can get all the necessary information/objects. In practice, this would mean to subclass the SavedRequestAwareAuthenticationSuccessHandler which is used by the default configuration, and the implemented behavior of which you most probably would want to keep. In the configuration you can then wire up that class with the <form-login authentication-success-handler-ref="..."> attribute.

Categories : Java



© Copyright 2017 w3hello.com Publishing Limited. All rights reserved.