springboot 接入cas-client-core单点登录

  • 1.maven引入相关包
    <dependency>
        <groupId>net.unicon.cas</groupId>
    	<artifactId>cas-client-autoconfig-support</artifactId>
    	<version>1.4.0-GA</version>
    </dependency>
    <dependency>
    	<groupId>org.jasig.cas.client</groupId>
    	<artifactId>cas-client-core</artifactId>
    	<version>3.2.1</version>
    </dependency>

     

  • 2.application.properties 文件配置
    #pro
    #cas.server-url-prefix=http://host/authserver
    #cas.server-login-url=http://host/authserver/login
    #cas.client-host-url=http://127.0.0.1
    #cas.use-session=true
    #cas.validation-type=cas
    #casClientLogoutUrl=http://host/logout?service=http://127.0.0.1/bigdata/user/logout/success
    
    #dev
    cas.server-url-prefix=http://192.168.102.198:9999/cas-server
    cas.server-login-url=http://192.168.102.198:9999/cas-server/login
    cas.client-host-url=http://192.168.102.198:8888
    cas.use-session=true
    cas.validation-type=cas
    casClientLogoutUrl=http://192.168.102.198:9999/cas-server/logout?service=http://192.168.102.198:8888/bigdata/user/logout/success

     

  • 3.过滤器授权访问cas跳转
    package com.sunmnet.bigdata.web.config;
    
    import java.util.HashMap;
    import java.util.Map;
    
    import org.jasig.cas.client.authentication.AuthenticationFilter;
    import org.springframework.boot.context.properties.ConfigurationProperties;
    import org.springframework.boot.web.servlet.FilterRegistrationBean;
    import org.springframework.context.annotation.Bean;
    import org.springframework.stereotype.Component;
    
    @Component
    @ConfigurationProperties(prefix = "cas")
    public class CASAutoConfig {
        private String serverUrlPrefix;
        
        private String serverLoginUrl;
        
        private String clientHostUrl;
        
        private String clientLogoutUrl;
    
        public String getServerUrlPrefix() {
    		return serverUrlPrefix;
    	}
    
    	public void setServerUrlPrefix(String serverUrlPrefix) {
    		this.serverUrlPrefix = serverUrlPrefix;
    	}
    
    	public String getServerLoginUrl() {
    		return serverLoginUrl;
    	}
    
    	public void setServerLoginUrl(String serverLoginUrl) {
    		this.serverLoginUrl = serverLoginUrl;
    	}
    
    	public String getClientHostUrl() {
    		return clientHostUrl;
    	}
    
    	public void setClientHostUrl(String clientHostUrl) {
    		this.clientHostUrl = clientHostUrl;
    	}
    	
    	
    
    	public String getClientLogoutUrl() {
    		return clientLogoutUrl;
    	}
    
    	public void setClientLogoutUrl(String clientLogoutUrl) {
    		this.clientLogoutUrl = clientLogoutUrl;
    	}
    
    	/**
         * 授权过滤器
         * @return
         */
        @Bean
        public FilterRegistrationBean filterAuthenticationRegistration() {
            FilterRegistrationBean registration = new FilterRegistrationBean();
            registration.setFilter(new AuthenticationFilter());
            // 设定匹配的路径
            registration.addUrlPatterns("/bigdata/user/login");
            Map<String,String> initParameters = new HashMap<String, String>();
            initParameters.put("casServerLoginUrl", serverUrlPrefix);
            initParameters.put("serverName", clientHostUrl);
            //忽略的url,"|"分隔多个url
            initParameters.put("ignorePattern", "/bigdata/user/logout/success");
            registration.setInitParameters(initParameters);
            // 设定加载的顺序
            registration.setOrder(1);
            return registration;
        }
        
    }
    

     

  • 4.启动器加入@EnableCasClient 配置
    import net.unicon.cas.client.configuration.EnableCasClient;
    @SpringBootConfiguration
    @EnableAspectJAutoProxy
    @EnableTransactionManagement
    @EnableScheduling
    @EnableCasClient
    public class BigDataApplication {
        public static void main(String[] args) {
            SpringApplication.run(BigDataApplication.class, args);
        }
    
    }
  • 5.controller参考
     

    package com.sunmnet.bigdata.web.controller;
    
    import java.io.IOException;
    import java.net.URLEncoder;
    import java.util.List;
    
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import javax.ws.rs.QueryParam;
    
    import org.jasig.cas.client.authentication.AttributePrincipal;
    import org.jasig.cas.client.util.AbstractCasFilter;
    import org.jasig.cas.client.validation.Assertion;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.http.MediaType;
    import org.springframework.web.bind.annotation.RequestBody;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestMethod;
    import org.springframework.web.bind.annotation.RestController;
    
    import com.sunmnet.bigdata.web.model.dto.user.Menu;
    import com.sunmnet.bigdata.web.model.dto.user.User;
    import com.sunmnet.bigdata.web.model.po.user.SecRole;
    import com.sunmnet.bigdata.web.model.po.user.SecUser;
    import com.sunmnet.bigdata.web.model.po.user.UserParam;
    import com.sunmnet.bigdata.web.service.impl.MenuService;
    import com.sunmnet.bigdata.web.service.impl.SecRoleService;
    import com.sunmnet.bigdata.web.service.impl.SecUserService;
    @RestController
    @RequestMapping(value = "/user",produces = MediaType.APPLICATION_JSON_UTF8_VALUE,name= "UserController")
    public class UserController extends BaseController{
    	@Value("${casClientLogoutUrl}")
        private String clientLogoutUrl;
    	
    	@Value("${cas.client-host-url}")
    	private String host;
    	
    	@Value("${security.default-user-password}")
    	private String defaultPassword;
    	
    	@Autowired
    	private MenuService menuService;
    	@Autowired
    	private SecUserService secUserService;
    	@Autowired
    	private SecRoleService secRoleService;
    	
    	@RequestMapping(value = "/login", method = RequestMethod.POST)
    	public Object login(@RequestBody UserParam param) throws IOException {
    		SecUser result = secUserService.getByUsername(param.getUsername());
    		if(result!=null) {
    			User user = result.coverUser();
    			SecRole role = secRoleService.getByUserId(user.getId());
    			user.setRoleId(role.getId());
    			user.setRoles(role.getRoleName());
    			List<Menu> menuList = menuService.getAllAuthorizedMenuTreeOfUser(result.getId());
    			user.setMenus(menuList);
    			request.getSession().setAttribute("user", user);
    			return buildSuccJson(user);
    		}else {
    			return buildErrJson("用户不存在");
    		}
    		
    	}
    	
    	@RequestMapping(value = "/logout", method = RequestMethod.GET)
    	public Object logout(HttpServletRequest request,HttpServletResponse response) throws IOException {
    		request.getSession().invalidate();
    		return buildSuccJson();
    	}
    	
    	@RequestMapping(value = "/cas_logout", method = RequestMethod.GET)
    	public void cas_logout(HttpServletRequest request,HttpServletResponse response) throws IOException {
    		request.getSession().invalidate();
    		response.sendRedirect(host+"/#/LoginPage");
    	}
    	
    	@RequestMapping(value = "/cas_login", method = RequestMethod.GET)
    	public void casLogin(@QueryParam("")UserParam param) throws IOException {
    		Assertion assertion = (Assertion) request.getSession().getAttribute(AbstractCasFilter.CONST_CAS_ASSERTION);
    		if(assertion!=null) {
    			AttributePrincipal principal = assertion.getPrincipal();
                //获取用户名
                String userName = principal.getName();
                SecUser result = secUserService.getByUsername(userName);
        		if(result!=null) {
                	response.sendRedirect(host+"/#/LoginPage?signIn=true&userName="+userName+"&password="+defaultPassword);
        		}else {
                	response.sendRedirect(host+"/#/LoginPage?signIn=false&errorCode=500&msg="+ URLEncoder.encode("该用户不存在本系统", "UTF-8"));
                }
    		}else {
    			response.sendRedirect(host+"/#/LoginPage?signIn=false&errorCode=500&msg="+ URLEncoder.encode("统一登录服务异常", "UTF-8"));
    		}
    	}
    }
    

    注意:退出登录时cas需要前端用href指向,才能指向跳转返回到service指向的方法

  • 5
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
可以使用Spring Security CAS扩展来实现。在pom.xml文件中添加以下依赖项: ``` <dependency> <groupId>org.springframework.security.extensions</groupId> <artifactId>spring-security-cas</artifactId> <version>1.0.7.RELEASE</version> </dependency> ``` 然后在application.properties文件中添加以下配置: ``` # CAS server URL cas.server.url=https://cas.example.com/cas # CAS server login URL cas.server.login.url=https://cas.example.com/cas/login # CAS server logout URL cas.server.logout.url=https://cas.example.com/cas/logout # CAS service URL cas.service.url=http://localhost:8080/login/cas # CAS service name cas.service.name=MyApp # CAS service login URL cas.service.login.url=http://localhost:8080/login # CAS service logout URL cas.service.logout.url=http://localhost:8080/logout # CAS service validate URL cas.service.validate.url=https://cas.example.com/cas/serviceValidate # CAS service ticket parameter name cas.service.ticket.parameterName=ticket # CAS service renew parameter name cas.service.renew.parameterName=renew # CAS service gateway parameter name cas.service.gateway.parameterName=gateway # CAS service artifact parameter name cas.service.artifact.parameterName=artifact # CAS service proxy callback URL cas.service.proxy.callbackUrl=http://localhost:8080/proxyCallback # CAS service proxy callback parameter name cas.service.proxy.callbackParameterName=pgtIou # CAS service proxy granting ticket parameter name cas.service.proxy.grantingTicket.parameterName=pgtIou # CAS service proxy granting ticket storage class cas.service.proxy.grantingTicket.storageClass=org.jasig.cas.client.proxy.ProxyGrantingTicketStorageImpl # CAS service proxy granting ticket storage file cas.service.proxy.grantingTicket.storageFile=/tmp/cas-proxy-granting-tickets # CAS service proxy granting ticket storage clean interval cas.service.proxy.grantingTicket.storageCleanInterval=3600000 # CAS service proxy granting ticket storage clean up cas.service.proxy.grantingTicket.storageCleanUp=true # CAS service proxy granting ticket storage clean up interval cas.service.proxy.grantingTicket.storageCleanUpInterval=3600000 # CAS service proxy granting ticket storage clean up max age cas.service.proxy.grantingTicket.storageCleanUpMaxAge=7200000 ``` 然后在Spring Boot应用程序中添加以下配置类: ``` @Configuration @EnableWebSecurity @EnableCasSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private CasAuthenticationEntryPoint casAuthenticationEntryPoint; @Autowired private CasAuthenticationProvider casAuthenticationProvider; @Autowired private SingleSignOutFilter singleSignOutFilter; @Autowired private CasAuthenticationFilter casAuthenticationFilter; @Autowired private CasProperties casProperties; @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .antMatchers("/login").permitAll() .anyRequest().authenticated() .and() .exceptionHandling() .authenticationEntryPoint(casAuthenticationEntryPoint) .and() .logout() .logoutUrl("/logout") .logoutSuccessUrl("/") .addLogoutHandler(new SingleSignOutHandler(casProperties.getServer().getLogoutUrl())) .and() .addFilterBefore(singleSignOutFilter, CasAuthenticationFilter.class) .addFilter(casAuthenticationFilter); } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.authenticationProvider(casAuthenticationProvider); } @Bean public ServiceProperties serviceProperties() { ServiceProperties serviceProperties = new ServiceProperties(); serviceProperties.setService(casProperties.getService().getUrl()); serviceProperties.setSendRenew(false); return serviceProperties; } @Bean public CasAuthenticationEntryPoint casAuthenticationEntryPoint() { CasAuthenticationEntryPoint casAuthenticationEntryPoint = new CasAuthenticationEntryPoint(); casAuthenticationEntryPoint.setLoginUrl(casProperties.getServer().getLoginUrl()); casAuthenticationEntryPoint.setServiceProperties(serviceProperties()); return casAuthenticationEntryPoint; } @Bean public CasAuthenticationProvider casAuthenticationProvider() { CasAuthenticationProvider casAuthenticationProvider = new CasAuthenticationProvider(); casAuthenticationProvider.setAuthenticationUserDetailsService(new UserDetailsServiceImpl()); casAuthenticationProvider.setServiceProperties(serviceProperties()); casAuthenticationProvider.setTicketValidator(new Cas30ServiceTicketValidator(casProperties.getServer().getUrl())); casAuthenticationProvider.setKey("casAuthenticationProviderKey"); return casAuthenticationProvider; } @Bean public SingleSignOutFilter singleSignOutFilter() { SingleSignOutFilter singleSignOutFilter = new SingleSignOutFilter(); singleSignOutFilter.setCasServerUrlPrefix(casProperties.getServer().getUrl()); singleSignOutFilter.setIgnoreInitConfiguration(true); return singleSignOutFilter; } @Bean public CasAuthenticationFilter casAuthenticationFilter() { CasAuthenticationFilter casAuthenticationFilter = new CasAuthenticationFilter(); casAuthenticationFilter.setAuthenticationManager(authenticationManager()); casAuthenticationFilter.setFilterProcessesUrl("/login/cas"); return casAuthenticationFilter; } } ``` 最后,在Spring Boot应用程序中添加以下服务类: ``` @Service public class UserDetailsServiceImpl implements AuthenticationUserDetailsService<CasAssertionAuthenticationToken> { @Override public UserDetails loadUserDetails(CasAssertionAuthenticationToken token) throws UsernameNotFoundException { String username = token.getName(); List<GrantedAuthority> authorities = AuthorityUtils.createAuthorityList("ROLE_USER"); return new User(username, "", authorities); } } ``` 现在,您可以使用Spring Boot应用程序调用CAS客户端自动配置支持来解析票据。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值