`
java4evero
  • 浏览: 47293 次
文章分类
社区版块
存档分类
最新评论
阅读更多

   




Recently I got a chance working with Spring security, formerly known as Acegi Security for spring.

While working with the framework, I heard comments from friends and colleagues saying that spring security lacks proper documentation.

So thought of sharing a little knowledge.

By the way, this is first ever blog posting and kindly excuse me and let me know any errors and improvements.

Spring security offers a simple configuration based security for your web applications helping you secure your web application with out littering your business logic with any security code.

It provides securing URL's based on the Role (Authorities), securing your business methods based on the ACL's.

The first step in hooking up the spring security to your web application is by specifying the DelegatingFilterProxy in your web.xml.

springSecurityFilterChain org.springframework.web.filter.DelegatingFilterProxy springSecurityFilterChain /* REQUEST INCLUDE FORWARD If you want to externalize all of your security related configuration into a separate file, you can do so and add that to your context location param.

contextConfigLocation /WEB-INF/beans.xml , /WEB-INF/springSecurity.xml Now comes the part of security configuration for your application, Adding the URL security patterns is pretty simple and straight forward.

Add all the URL patterns which you want to secure and add the wild card pattern at the end.

You need to have some default principal and role even for non logged in users as you need to give access to pages like log in, register and forgot password kind of functionality even to non logged in users.

I tried to add comments to pretty much every element which I am using here.

As an example I added just a wild card intercept url which make every page of my application secure.

You need to exclude different urls based on the roles.

Following is my custom implementation of AuthenticationEntryPoint, which currently is not doing any thing except leveraging the commence to its super class which is the spring implementation of AuthenticationProcessingFilterEntryPoint.

I hooked it to add any custom logic.



public class CustomAuthenticationEntryPoint extends AuthenticationProcessingFilterEntryPoint {

<span> </span>private static final Log logger = LogFactory.getLog(CustomAuthenticationEntryPoint.class);

<span> </span>@Override

<span> </span>public void commence(ServletRequest request, ServletResponse response, AuthenticationException authException) throws IOException, ServletException {

<span> </span>super.commence(request, response, authException);

<span> </span>}

}



This is my custom authentication manager which actually does the custom login of the user.

It will throw an BadCredentialsException in case of invalid credentials or thorws a AuthenticationServiceException in case of a service error (Database error, SQL error or any other error).



public class CustomAuthunticationManager implements AuthenticationManager {

<span> </span>@Autowired

<span> </span>UserManagerService userManagerService;

<span> </span>public Authentication authenticate(Authentication authentication) throws AuthenticationException {

<span> </span>if(StringUtils.isBlank((String) authentication.getPrincipal()) || StringUtils.isBlank((String) authentication.getCredentials())){

<span> </span>throw new BadCredentialsException("Invalid username/password");

<span> </span>}

<span> </span>User user = null;

<span> </span>GrantedAuthority[] grantedAuthorities = null;

<span> </span>try{

<span> </span>user = userManagerService.getUser((String) authentication.getPrincipal(), (String) authentication.getCredentials());

<span> </span>} catch(InvalidCredentialsException ex){

<span> </span>throw new BadCredentialsException(ex.getMessage());

<span> </span>} catch(Exception e){

<span> </span>throw new AuthenticationServiceException("Currently we are unable to process your request. Kindly try again later.");

<span> </span>}

<span> </span>

<span> </span>if (user != null) {

<span> </span>List roles = user.getAssociatedRoles();

<span> </span>grantedAuthorities = new GrantedAuthority[roles.size()];

<span> </span>for (int i = 0; i < roles.size(); i++) {

<span> </span>Role role = roles.get(i);

<span> </span>GrantedAuthority authority = new GrantedAuthorityImpl(role.getRoleCode());

<span> </span>grantedAuthorities[i] = authority;

<span> </span>}

<span> </span>} else{

<span> </span>throw new BadCredentialsException("Invalid username/password");

<span> </span>}

<span> </span>return new UsernamePasswordAuthenticationToken(user, authentication.getCredentials(), grantedAuthorities);

<span> </span>}

}



At the client side (jsp), the simple configuration you need to do is post the request to"/j_spring_security_check" with parameters "j_username" and "j_password".

That's pretty much all you need to do for enabling spring security to your existing web application.

I will try to explain about doing the method security using ACL's and configuring the view using spring security tags in another post.

 
0
0
分享到:
评论

相关推荐

    SpringSecurity-Jar包

    通过这个jar包,开发者可以使用Spring的注解来声明安全规则,例如`@Secured`和`@PreAuthorize`,以及在XML配置中使用 `&lt;http&gt;` 和 `&lt;authentication-manager&gt;` 元素。此模块还包含了一些自定义的Spring Bean定义,...

    01-SpringSecurity-Demo.zip

    SpringSecurity是Java开发中一个强大的安全框架,用于处理应用程序的安全性。它提供了全面的身份验证、授权和访问控制功能,能够帮助开发者构建安全的Web应用程序。本压缩包"01-SpringSecurity-Demo.zip"包含了...

    spring-security-core-3.1.0.RC1.jar

    3. **Filter Chain**:Spring Security通过一系列过滤器(Filter)实现请求的拦截和处理。在3.1.0.RC1中,这些过滤器如`DelegatingFilterProxy`、`ChannelProcessingFilter`、`SecurityContextPersistenceFilter`等...

    springsecurity所有jar包

    它包含安全元数据(如`@Secured`和`@PreAuthorize`注解)和XML配置元素,如`&lt;http&gt;`和`&lt;authentication-manager&gt;`,用于定义安全策略。 2. **spring-security-core**:这是Spring Security的基础模块,提供了安全...

    spring-security-oauth2与spring-security-web 3.1.2 源码

    Spring Security是Java领域中广泛应用的安全框架,用于保护Web应用程序免受各种安全威胁。OAuth2则是一种授权协议,常用于提供安全的第三方应用访问资源的权限。在这个源码分析中,我们将深入探讨`spring-security-...

    Spring Security-3中文官方文档

    在技术概述部分,Spring Security的运行环境和核心组件被详细解释,包括SecurityContextHolder、SecurityContext和Authentication对象,UserDetailsService接口,GrantedAuthority概念,以及验证和访问控制的流程。...

    spring-security-core-2.0.5.RELEASE.src

    1. **Authentication**(认证):Spring Security的核心组件之一是Authentication,它负责验证用户身份。在`org.springframework.security.authentication`包下,有多种认证机制,如...

    初识 Spring Security - v1.1.pdf

    &lt;security:authentication-provider user-service-ref="userDetailsService"&gt; &lt;security:password-encoder hash="bcrypt" /&gt; &lt;/security:authentication-provider&gt; &lt;/security:authentication-manager&gt; &lt;!-- ...

    毕业设计&课设_集成spring-boot-spring-security-jwt-authentication项目.zip

    该资源内项目源码是个人的课程设计、毕业设计,代码都测试ok,都是运行成功后才上传资源,答辩评审平均分达到96分,放心下载使用! ## 项目备注 1、该资源内项目代码都经过严格测试运行成功才上传的,请放心下载使用...

    thymeleaf-extras-springsecurity-3.0-master.zip

    #authentication representing the Spring Security authentication object (an object implementing the org.springframework.security.core.Authentication interface). #authorization: a expression utility ...

    spring-security-4.0.3.RELEASE-全包

    2. **Authentication**:Spring Security提供了一套完整的身份验证机制,包括Remember Me服务、基于表单的登录、以及支持各种认证源如LDAP、数据库等。4.0.3版本可能包含了改进的认证流程和错误处理。 3. **...

    spring-security源代码

    Spring Security 是一个强大的安全框架,主要用于Java应用的安全管理。它提供了认证、授权、访问控制以及CSRF防护等核心功能,广泛应用于Web应用和企业级系统。这个压缩包文件"spring-security-parent-2.0.4"是...

    spring-security-2.0.6. API和 jar包

    在XML配置中,你会看到 `&lt;http&gt;`、`&lt;authentication-manager&gt;` 和 `&lt;intercept-url&gt;` 等元素,它们分别用于定义安全过滤链、认证管理和URL访问规则。而在Java配置中,可以使用`@EnableWebSecurity`、`@Configuration...

    spring-security-3.0.5.RELEASE 官方下载

    在3.0.5.RELEASE中,可以使用`&lt;http&gt;`、`&lt;authentication-manager&gt;`和`&lt;intercept-url&gt;`等元素来配置安全行为。 5. **Remember Me服务**:此版本可能包含了Remember Me功能,允许用户在一段时间内无须重新登录。它...

    spring-boot-security

    3. **过滤器链(Filter Chain)**:Spring Security的核心组件之一是过滤器链,它由多个过滤器组成,如`UsernamePasswordAuthenticationFilter`和`HttpSessionAuthenticationStrategy`等。这些过滤器负责处理HTTP...

    spring-security-3.1.3.RELEASE.jar

    在实际应用中,Spring Security还提供了过滤器链(Filter Chain)的概念,这是实现Web安全的关键。每个过滤器都有特定的职责,例如,`HttpSessionAuthenticationStrategy`处理会话相关的认证,而`...

    Spring Security-3.0.1 中文官方文档(翻译版)

    在结构和实现方面,Spring Security提供了核心组件如SecurityContextHolder、SecurityContext和Authentication对象等,这些组件共同工作以提供应用程序的安全性上下文。此外,UserDetailsService负责加载用户特定...

    spring-security-taglibs-2.0.4.jar.zip

    4. `&lt;sec:authentication-properties&gt;`:这个标签允许开发者自定义与认证相关的属性,例如记住我(remember-me)功能。 5. `&lt;sec:csrf&gt;`:跨站请求伪造(CSRF)防护标签,防止恶意用户在用户浏览器中执行非预期的...

    spring-security-samples-contacts-2.0.4

    - **Filter Security Interceptor (FSI)**: 一系列Spring MVC过滤器,负责处理HTTP请求的安全性。 - **Security Context**: 存储当前用户的认证信息。 - **Authentication Manager**: 处理身份验证请求,验证用户...

Global site tag (gtag.js) - Google Analytics