pom.xml
@@ -146,11 +146,27 @@ <finalName>screen_api_v2</finalName> <plugins> <plugin> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-maven-plugin</artifactId> <version>1.3.2</version> <configuration> <!--配置文件的位置--> <configurationFile>src/main/resources/generatorConfig.xml</configurationFile> <verbose>true</verbose> <overwrite>false</overwrite> </configuration> <dependencies> <dependency> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-core</artifactId> <version>1.3.2</version> </dependency> </dependencies> </plugin> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project> src/main/java/com/moral/common/aop/ControllerAOP.java
@@ -52,29 +52,27 @@ Object target = pjp.getTarget(); Method currentMethod = target.getClass().getMethod(msig.getName(), msig.getParameterTypes()); Type type = currentMethod.getGenericReturnType(); String message = ""; String message = e.getMessage(); if (e instanceof BusinessException) { message = e.getLocalizedMessage(); } else if (e instanceof ValidateException) { message = e.getLocalizedMessage(); } else { log.error(pjp.getSignature() + " error ", e); message = e.toString(); log.error(pjp.getSignature() + " error: " + e.toString(), e); } if (type instanceof ParameterizedType) { Type rawType = ((ParameterizedType) type).getRawType(); if (rawType == AppData.class) { type = ((ParameterizedType) type).getRawType(); } if (type == AppData.class) { return new AppData(message,AppData.FAIL); } else if (rawType == ResultBean.class) { return new ResultBean(message,ResultBean.FAIL); } else if (rawType == Map.class) { } else if (type == ResultBean.class) { return new ResultBean(e); } else if (type == Map.class) { Map<String, Object> resultMap = new HashMap<String, Object>(); resultMap.put("msg", message); return resultMap; } } } else if (type == Void.TYPE) { return null; } else { return type.getClass().newInstance(); } } } src/main/java/com/moral/common/bean/ResultBean.java
@@ -17,24 +17,20 @@ private T data; public ResultBean() { super(); this.message = "success"; this.code = SUCCESS; } public ResultBean(Throwable e) { super(); this.message = e.toString(); this.code = FAIL; } public ResultBean(T data) { this(); this.message = "success"; this.code = SUCCESS; this.data = data; } public ResultBean(String message, int code) { super(); this.message = message; this.code = code; } src/main/java/com/moral/controller/AccountController.java
@@ -9,6 +9,7 @@ import javax.servlet.http.HttpServletRequest; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; @@ -44,4 +45,10 @@ Integer result = accountService.deleteAccountsByLogic(ids); return new ResultBean<Integer>(result); } @GetMapping("{accountName}") public ResultBean<Integer> getAccountCountByAccountName(@PathVariable("accountName") String accountName) { Integer result = accountService.getAccountCountByAccountName(accountName); return new ResultBean<Integer>(result); } } src/main/java/com/moral/controller/OrganizationController.java
@@ -5,6 +5,9 @@ import com.moral.entity.Organization; import com.moral.service.OrganizationService; import org.springframework.web.bind.annotation.*; import java.util.List; import javax.annotation.Resource; @RestController @@ -28,4 +31,11 @@ ResultBean resultBean = new ResultBean(ResultBean.SUCCESS); return resultBean; } @GetMapping("list/{name}") public ResultBean<List<Organization>> getOrganizationsByName(@PathVariable("name") String name) { List<Organization> organizations = organizationService.getOrganizationsByName(name); return new ResultBean<List<Organization>>(organizations); } } src/main/java/com/moral/controller/TokenControllers.java
New file @@ -0,0 +1,48 @@ package com.moral.controller; import java.util.HashMap; import java.util.Map; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import org.springframework.util.ObjectUtils; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RestController; import com.moral.service.TokenService; @RestController public class TokenControllers { @Resource private TokenService tokenService; @GetMapping("oauth/token/{type}/{username}/{password}") public Map<String, Object> getAuthToken(@PathVariable("username") String username, @PathVariable("password") String password, @PathVariable("type") String type, HttpServletRequest request) { Map<String, Object> result = new HashMap<String, Object>(); if (ObjectUtils.isEmpty(username) || ObjectUtils.isEmpty(password) || ObjectUtils.isEmpty(type)) { result.put("msg", "参数输入不合法"); } else { String url = request.getRequestURL().toString().replace(request.getRequestURI(), "") + request.getContextPath(); String realPath = request.getServletContext().getRealPath("/"); result = tokenService.getAuthToken(type, username, password, url); } return result; } @PostMapping("oauth/token/{refresh_token}") public Map<String, Object> getAuthToken(@PathVariable("refresh_token") String refresh_token,HttpServletRequest request) { Map<String, Object> result = new HashMap<String, Object>(); if (ObjectUtils.isEmpty(refresh_token)) { result.put("msg", "参数输入不合法"); } else { String url = request.getRequestURL().toString().replace(request.getRequestURI(), "") + request.getContextPath(); result = tokenService.getAuthToken(refresh_token, url); } return result; } } src/main/java/com/moral/entity/Account.java
@@ -68,5 +68,7 @@ * @mbggenerated Thu Dec 07 16:17:21 CST 2017 */ private Date expireTime; private Organization organization; } src/main/java/com/moral/security/AuthorizationServerConfiguration.java
@@ -4,6 +4,7 @@ import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.annotation.Configuration; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer; import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter; import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer; @@ -17,6 +18,9 @@ public class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter { private static String REALM = "MY_OAUTH_REALM"; @Autowired private UserDetailsService userDetailsService; @Autowired private TokenStore tokenStore; @@ -43,7 +47,10 @@ @Override public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception { endpoints.tokenStore(tokenStore).userApprovalHandler(userApprovalHandler).authenticationManager(authenticationManager); endpoints.tokenStore(tokenStore) .userApprovalHandler(userApprovalHandler) .authenticationManager(authenticationManager) .userDetailsService(userDetailsService); } @Override src/main/java/com/moral/security/ResourceServerConfiguration.java
@@ -27,5 +27,23 @@ .authorizeRequests() .antMatchers("/test/**").permitAll() .and().exceptionHandling().accessDeniedHandler(new OAuth2AccessDeniedHandler()); /*http.requestMatchers() .antMatchers("/screen/**") .and() .authorizeRequests() .antMatchers("/screen/**").permitAll() .and() .exceptionHandling() .accessDeniedHandler(new OAuth2AccessDeniedHandler());*/ /*http.requestMatchers() .antMatchers("/mobile/**") .and() .authorizeRequests() .antMatchers("/mobile/**").permitAll() .and() .exceptionHandling() .accessDeniedHandler(new OAuth2AccessDeniedHandler());*/ } } src/main/java/com/moral/security/WebSecurityConfiguration.java
@@ -14,6 +14,7 @@ import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.crypto.password.NoOpPasswordEncoder; import org.springframework.security.oauth2.provider.ClientDetailsService; import org.springframework.security.oauth2.provider.approval.ApprovalStore; import org.springframework.security.oauth2.provider.approval.TokenApprovalStore; @@ -44,7 +45,7 @@ .withUser("bill").password("abc123").roles("ADMIN").and() .withUser("bob").password("abc123").roles("USER"); // auth.userDetailsService(userDetailsService).passwordEncoder(new Md5PasswordEncoder()); auth.userDetailsService(userDetailsService).passwordEncoder(NoOpPasswordEncoder.getInstance()); } @Override src/main/java/com/moral/service/AccountService.java
@@ -20,4 +20,6 @@ Integer deleteAccountsByLogic(List<Integer> ids); Integer getAccountCountByAccountName(String accountName); } src/main/java/com/moral/service/OrganizationService.java
@@ -18,4 +18,7 @@ public void addOrModify(Organization organization); public void deleteByIds(Integer... ids); List<Organization> getOrganizationsByName(String name); } src/main/java/com/moral/service/TokenService.java
New file @@ -0,0 +1,11 @@ package com.moral.service; import java.util.Map; public interface TokenService { Map<String, Object> getAuthToken(String type, String username, String password, String url); Map<String, Object> getAuthToken(String token, String url); } src/main/java/com/moral/service/impl/AccountServiceImpl.java
@@ -26,7 +26,9 @@ import com.moral.common.util.Crypto; import com.moral.common.util.ResourceUtil; import com.moral.entity.Account; import com.moral.entity.Organization; import com.moral.mapper.AccountMapper; import com.moral.mapper.OrganizationMapper; import com.moral.service.AccountService; import com.moral.service.OrganizationService; @@ -41,6 +43,9 @@ @Resource private OrganizationService organizationService; @Resource private OrganizationMapper organizationMapper; @Override public Map<String, Object> screenLogin(Map<String, Object> parameters) { @@ -109,6 +114,12 @@ } PageHelper.startPage(Integer.valueOf((String) parameters.get("pageIndex")), Integer.valueOf((String) parameters.get("pageSize"))); List<Account> accounts = accountMapper.selectByExample(example); for (Account account : accounts) { if (!ObjectUtils.isEmpty(account.getOrganizationId())) { Organization organization = organizationMapper.selectByPrimaryKey(account.getOrganizationId()); account.setOrganization(organization); } } return new PageBean<Account>(accounts); } @@ -135,4 +146,11 @@ return accountMapper.updateByExampleSelective(account, example); } @Override public Integer getAccountCountByAccountName(String accountName) { Account account = new Account(); account.setAccountName(accountName); return accountMapper.selectCount(account); } } src/main/java/com/moral/service/impl/AuthUserServiceImpl.java
@@ -1,38 +1,58 @@ package com.moral.service.impl; import com.moral.entity.auth.AuthRole; import com.moral.entity.auth.AuthUser; //import com.moral.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Map; import javax.annotation.Resource; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Service; import java.util.Collection; import java.util.HashSet; import java.util.Iterator; import com.moral.common.util.RedisUtil; import com.moral.entity.Account; import com.moral.entity.OperateUser; import com.moral.mapper.AccountMapper; import com.moral.service.AccountService; import com.moral.service.OperateUserService; @Service public class AuthUserServiceImpl implements UserDetailsService { // @Autowired // private UserService userService; @Resource private AccountMapper accountMapper; @Resource private AccountService accountService; @Resource private OperateUserService operateUserService; @Resource private RedisTemplate<String, String> redisTemplate; @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { // AuthUser user = userService.findByUsername(username); AuthUser user = null; if(user == null){ throw new UsernameNotFoundException("用户名:"+ username + "不存在!"); } String type = RedisUtil.get(redisTemplate, "token_" + username), password; Collection<SimpleGrantedAuthority> collection = new HashSet<SimpleGrantedAuthority>(); Iterator<AuthRole> iterator = user.getList().iterator(); while (iterator.hasNext()){ collection.add(new SimpleGrantedAuthority(iterator.next().getRole_name())); if ("screen".equals(type)) { Account account = accountService.getAccountByAccountName(username); password = account.getPassword(); List<Map<String, Object>> roleNames = accountMapper.getRoleNameByAccountId(account.getId()); for (Map<String, Object> roleName : roleNames) { collection.add(new SimpleGrantedAuthority((String) roleName.get("role_name"))); } return new org.springframework.security.core.userdetails.User(username, user.getPassword(), collection); } else { OperateUser operateUser = operateUserService.getOperateUserByMobile(username); password = operateUser.getPassword(); collection.add((new SimpleGrantedAuthority("ROLE_MOBILE"))); } return new User(username, password, collection); } } src/main/java/com/moral/service/impl/OrganizationServiceImpl.java
@@ -1,9 +1,9 @@ package com.moral.service.impl; import com.github.pagehelper.PageHelper; import com.moral.common.bean.Constants; import com.moral.common.bean.PageBean; import com.moral.common.util.ExampleUtil; import com.moral.common.util.MyBatisBaseMapUtil; import com.moral.common.util.ValidateUtil; import com.moral.entity.Organization; import com.moral.entity.exp.OrganizationExp; @@ -13,7 +13,7 @@ import com.moral.service.OrganizationService; import org.springframework.stereotype.Service; import tk.mybatis.mapper.entity.Example; import tk.mybatis.mapper.mapperhelper.SqlHelper; import tk.mybatis.mapper.entity.Example.Criteria; import javax.annotation.Resource; import java.util.*; @@ -58,7 +58,6 @@ public PageBean queryByPageBean(PageBean pageBean){ Example example = ExampleUtil.generateExample(ENTITY_CLASS,pageBean); //me List<Example.Criteria> criteriaList = example.getOredCriteria(); if(criteriaList!=null&&criteriaList.size()>0){ for(Example.Criteria cri : criteriaList){ @@ -68,8 +67,8 @@ example.or().andNotEqualTo("isDelete","1"); } PageHelper.startPage(pageBean.getPageIndex(),pageBean.getPageSize()); List page = organizationMapper.selectWithAreaNameByExample(example); return new PageBean(page); List<OrganizationExp> organizationExpandList = organizationMapper.selectWithAreaNameByExample(example); return new PageBean(organizationExpandList); } public void addOrModify(Organization organization){ try{ @@ -102,4 +101,15 @@ } } @Override public List<Organization> getOrganizationsByName(String name) { Example example = new Example(Organization.class); Criteria criteria = example.createCriteria(); criteria.andLike("name", "%" + name + "%"); criteria.andEqualTo("isDelete", Constants.IS_DELETE_FALSE); List<Organization> organizations = organizationMapper.selectByExample(example); return organizations; } } src/main/java/com/moral/service/impl/TokenServiceImpl.java
New file @@ -0,0 +1,110 @@ package com.moral.service.impl; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import javax.annotation.Resource; import org.apache.commons.codec.binary.Base64; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.stereotype.Service; import org.springframework.util.ObjectUtils; import org.springframework.web.client.RestTemplate; import com.moral.common.bean.Constants; import com.moral.common.util.Crypto; import com.moral.common.util.RedisUtil; import com.moral.entity.Account; import com.moral.entity.OperateUser; import com.moral.service.AccountService; import com.moral.service.OperateUserService; import com.moral.service.TokenService; @Service @SuppressWarnings({ "unchecked", "rawtypes" }) public class TokenServiceImpl implements TokenService { private static final String AUTH_SERVER_URI = "/oauth/token?grant_type=password&username={username}&password={password}"; private static final String REFRESH_SERVER_URI = "/oauth/token?grant_type=refresh_token&refresh_token={refresh_token}"; @Resource private AccountService accountService; @Resource private OperateUserService operateUserService; @Resource private RedisTemplate<String, String> redisTemplate; @Override public Map<String, Object> getAuthToken(String type, String username, String password, String url) { Map<String, Object> result = new HashMap<String, Object>(); password = Crypto.md5(password); if ("screen".equals(type)) { Account account = accountService.getAccountByAccountName(username); if (ObjectUtils.isEmpty(account)) { result.put("msg", "用户名输入有误"); return result; } else { if (!password.equals(account.getPassword())) { result.put("msg", "密码输入有误"); return result; } if (Constants.IS_DELETE_TRUE.equals(account.getIsDelete())) { result.put("msg", "您的账号已禁用,请联系管理员!"); return result; } result.put("accountId", account.getId()); } } else if ("mobile".equals(type)) { OperateUser operateUser = operateUserService.getOperateUserByMobile(username); if (ObjectUtils.isEmpty(operateUser)) { result.put("msg", "用户名输入有误"); return result; } else { if (!password.equals(operateUser.getPassword())) { result.put("msg", "密码输入有误"); return result; } result.put("userId", operateUser.getId()); } } else { result.put("msg", "类型输入有误"); return result; } RedisUtil.set(redisTemplate, "token_" + username, type); RestTemplate restTemplate = new RestTemplate(); HttpEntity<String> httpEntity = new HttpEntity<String>(getHeadersWithClientCredentials()); Map map = restTemplate.postForObject(url + AUTH_SERVER_URI, httpEntity, Map.class, username, password); result.putAll(map); return result; } @Override public Map<String, Object> getAuthToken(String refresh_token, String url) { HttpEntity<String> httpEntity = new HttpEntity<String>(getHeadersWithClientCredentials()); RestTemplate restTemplate = new RestTemplate(); Map map = restTemplate.postForObject(url + REFRESH_SERVER_URI, httpEntity, Map.class, refresh_token); return map; } private static HttpHeaders getHeaders() { HttpHeaders headers = new HttpHeaders(); headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON)); return headers; } private static HttpHeaders getHeadersWithClientCredentials() { String plainClientCredentials = "my-trusted-client:secret"; String base64ClientCredentials = new String(Base64.encodeBase64(plainClientCredentials.getBytes())); HttpHeaders headers = getHeaders(); headers.add("Authorization", "Basic " + base64ClientCredentials); return headers; } }